2017-06-12 374 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的面向对象模式。 –

相关问题