pandas plot bar,其中一列值为Xaxis

时间:2017-02-10 08:52:29

标签: python pandas plot

      A          B                  C             D         date
0  53936248   53928376            7840          2800     17-02-10
1  22936276   53928404            7840          2800     17-02-11
2  523763     53928404            7840          2800     17-02-12

如何使用pandas绘图栏,日期值为Xaxis。

像这样:

enter image description here

2 个答案:

答案 0 :(得分:1)

我认为您首先需要将列date to_datetime转换为year

然后set_index和最后DataFrame.plot.bar

df.date = pd.to_datetime(df.date).dt.year
df = df.set_index('date')
df.index.name= None
print (df)
             A         B     C     D
2010  53936248  53928376  7840  2800
2011  22936276  53928404  7840  2800
2012    523763  53928404  7840  2800

df.plot.bar(rot=0)

graph

如果你用魔杖绘制dates

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

df.date = pd.to_datetime(df.date)
df = df.set_index('date')
df.index.name= None
print (df)
                   A         B     C     D
2010-02-17  53936248  53928376  7840  2800
2011-02-17  22936276  53928404  7840  2800
2012-02-17    523763  53928404  7840  2800

ax = df.plot.bar(rot=45)
ticklabels = df.index.strftime('%Y-%m-%d')
ax.xaxis.set_major_formatter(ticker.FixedFormatter(ticklabels))
plt.show()

graph1

答案 1 :(得分:1)

假设date已经datetime

df.assign(year=df.date.dt.year) \
  .set_index('year').drop('date', 1) \
  .rename_axis([None]).plot.bar(rot=0)

enter image description here