如何绘制DataFrames?在Python中

时间:2016-06-15 16:59:06

标签: python pandas plot dataframe

我正在尝试绘制一个DataFrame,但我没有得到我需要的结果。这是我正在尝试做的以及我目前正在做的事情的一个例子。 (我是Python新手)

import pandas as pd
import matplotlib.pyplot as plt

my_data = {1965:{'a':52, 'b':54, 'c':67, 'd':45}, 
      1966:{'a':34, 'b':34, 'c':35, 'd':76}, 
      1967:{'a':56, 'b':56, 'c':54, 'd':34}}  

df = pd.DataFrame(my_data)
df.plot( style=[])
plt.show()

我得到了下面的图表,但我需要的是:X轴上的年份和每一行必须是当前在X轴上的年份(a,b,c,d)。谢谢你的帮助!!。

enter image description here

2 个答案:

答案 0 :(得分:1)

import pandas as pd
import matplotlib.pyplot as plt

my_data = {1965:{'a':52, 'b':54, 'c':67, 'd':45}, 
      1966:{'a':34, 'b':34, 'c':35, 'd':76}, 
      1967:{'a':56, 'b':56, 'c':54, 'd':34}}  

df = pd.DataFrame(my_data)
df.T.plot( kind='bar') # or df.T.plot.bar()
plt.show()

enter image description here

更新

如果这是你想要的:

df = pd.DataFrame(my_data)
df.columns=[str(x) for x in df.columns] # convert year numerical values to str
df.T.plot()
plt.show()

enter image description here

答案 1 :(得分:1)

你可以这样做:

ax = df.T.plot(linewidth=2.5)

plt.locator_params(nbins=len(df.columns))

ax.xaxis.set_major_formatter(mtick.FormatStrFormatter('%4d'))

enter image description here