2017-06-12 377 views
0

我的Python熊貓數據幀是這樣的:如何繪製(在matplotlib中)包含兩列,時間序列和值之一的python熊貓數據框?

enter image description here

我想繪製在X軸和值在Y軸 日期我能得到它一次一個。 X軸或Y軸。我希望他們在一個圖中。

我已經試過這樣的事情:

import pandas as pd 
from pandas import Series, DataFrame, Panel 
from mysql.connector import MySQLConnection, Error 
from python_mysql_dbconfig import read_db_config 
import matplotlib.pyplot as plt 

dbconfig = read_db_config() 
conn = MySQLConnection(**dbconfig) 
cur = conn.cursor() 

df_mysql = pd.read_sql('SELECT PO_Date,PO_Total FROM purchase_order',con=conn) 

print df_mysql 
po_dates = df_mysql.ix[:,0] 
po_total = df_mysql.ix[:,1] 

X = Series(po_total,index=po_dates) 
X.plot() 
plt.show() 

conn.close() 

如何將這些2列繪製在一起嗎?

回答

0

它可以更容易和原生:

df_mysql.columns = ['po_date','po_total'] 
df_mysql.plot('po_date','po_total') 

第一行(列名分配)可以作爲參數加載過程本身來完成 - pd.read_sql(<args>, columns = ['po_date','po_total'])

+1

謝謝。效果不錯:) –

+0

你可以在兩行中使用兩次繪圖函數。 ''matplotlib''在默認情況下保留現有的圖形,並讓您一起呈現幾條趨勢線。 ''df_mysql.columns = [ 'po_date', 'po_total1',po_total2 ']'' ''df_mysql.plot(' po_date ' 'po_total1')'' ''df_mysql.plot(' po_date','po_total2')'' – Dimgold

0
X = Series(po_total.values,index=po_dates) 
    X.plot() 
+0

謝謝。完美工作。錯過了那件小事。 –

+0

你能把這個標記爲答案嗎? – Linda

+0

我已經標記過它,但似乎Dimgold的答案更準確。我希望我可以標記兩個。 :P –

0

您可能需要將日期數據轉換爲datetime format

以下是一個示例:

import pandas as pd 
# To obtain stock data online, import pandas.io.data namespace, alias as web 
from pandas_datareader import data, wb 

# datetime for the dates 
import datetime 
import matplotlib.pyplot as plt 

# start end end dates 
start = datetime.datetime(2017, 1, 1) 
end = datetime.datetime(2017, 6, 9) 

# read from Google finance and display the first five rows 
ibm = data.DataReader("IBM", 'google', start, end) 
ibm.head() 

# Create a figure and add an axes in which to plot the data 
fig1 = plt.figure(figsize = (5, 3)) 
ax1 = fig1.add_subplot(1,1,1) 

# Define the variables you wish to plot 
# The web data reader indexes the dataframe by date; get_level_values 
# retrieves those dates from the index 
x = ibm.index.get_level_values(0) 
y = ibm.Close 

ax1.plot(x, y, color = '0.5') 

plt.show() 
+0

我的數據已經是日期時間格式。 「datetime.date」是特定的。不管怎麼說,還是要謝謝你。琳達的解決方案是我正在尋找的, –

+0

很高興你的問題解決了。不過,請檢查使用Matplotlib的面向對象模式。 –

相關問題