如何绘制(在matplotlib中)python pandas数据帧包含两列,一个时间序列和一个值?

时间:2017-06-12 09:40:03

标签: python pandas matplotlib graph data-analysis

我的Python Pandas Dataframe看起来像这样:

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()

如何将这两列一起绘制?

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

它可以更容易和原生:

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

第一行(列名称赋值)可以在加载过程中作为参数完成 - pd.read_sql(<args>, columns = ['po_date','po_total'] )

答案 2 :(得分: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()