在Matplotlib中按年绘制条形图

问题描述 投票:0回答:1

[我正在尝试绘制此DataFrame,该DataFrame记录年度系列中的各种金额:

from matplotlib.dates import date2num

jp = pd.DataFrame([1000,2000,2500,3000,3250,3750,4500], index=['2011','2012','2013','2014','2015','2016','2017'])
jp.index = pd.to_datetime(jp.index, format='%Y')
jp.columns = ['Money']

我只想使用PyPlot(即pyplot.bar)以此制作条形图。

我尝试过:

plt.figure(figsize=(15,5))

xvals = date2num(jp.index.date)
yvals = jp['Money']
plt.bar(xvals, yvals, color='black')

ax = plt.gca()
ax.xaxis_date()

plt.show()

但是图表显示如下:

weird bar chart

  1. 酒吧在哪里?我觉得这张图将数据归因于一年的第一天(例如2011年1月1日),因此每个“条”之间的巨大空间和条的细度。
  2. 知道这是一个年度系列,我如何正确绘制呢?理想情况下,y轴仅包含年份。某事告诉我,我不需要使用date2num(),因为这似乎是非常常见的普通绘图作业。

这让我困惑了两天。我在网上找到的所有解决方案似乎都使​​用DataFrame.plot,但我宁愿学习如何正确使用PyPlot。我还打算再添加两组标记,这似乎是最常见的方法是通过plt.bar()

谢谢大家。

python pandas matplotlib
1个回答
0
投票

您可以这样做

jp.plot.bar()

给出:

enter image description here

或根据实际年份绘制:

plt.bar(jp.index.year, jp.Money)

给出:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.