简体   繁体   English

在 Matplotlib 中按年份绘制条形图

[英]Plotting Bar Graph by Years in Matplotlib

I am trying to plot this DataFrame which records various amounts of money over a yearly series:我正在尝试 plot 这个 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']

I would simply like to make a bar graph out of this using PyPlot (ie pyplot.bar).我只想使用 PyPlot(即 pyplot.bar)制作一个条形图。

I tried:我试过了:

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

But the chart turns out like this:但图表结果是这样的:

奇怪的条形图

  1. Only by increasing the width substantially will I start seeing the bars.只有大幅增加宽度,我才会开始看到条形图。 I have a feeling that this graph is attributing the data to the first date of the year (2011-01-01 for example), hence the massive space between each 'bar' and the thinness of the bars.我有一种感觉,这张图将数据归因于一年中的第一个日期(例如 2011-01-01),因此每个“条”之间的巨大空间和条的细度。
  2. How can I plot this properly, knowing that this is a yearly series?知道这是一个年度系列,我怎么能正确 plot? Ideally the y-axis would contain only the years.理想情况下,y 轴只包含年份。 Something tells me that I do not need to use date2num() , since this seems like a very common, ordinary plotting exercise.有些东西告诉我我不需要使用date2num() ,因为这似乎是一个非常常见的普通绘图练习。
  3. My guess as to where I'm stuck is not handling the year correctly.我对我被困在哪里的猜测没有正确处理这一年。 As of now I have them as DateTimeIndex, but maybe there are other steps I need to take.到目前为止,我将它们作为 DateTimeIndex,但也许我需要采取其他步骤。

This has puzzled me for 2 days.这让我困惑了2天。 All solutions I found online seems to use DataFrame.plot , but I would rather learn how to use PyPlot properly.我在网上找到的所有解决方案似乎都使用DataFrame.plot ,但我宁愿学习如何正确使用 PyPlot。 I also intend to add two more sets of bars, and it seems like the most common way to do that is through plt.bar() .我还打算再添加两组条,似乎最常见的方法是通过plt.bar()

Thanks everyone.感谢大家。

You can either do你可以做

jp.plot.bar()

which gives:这使:

在此处输入图像描述

or plot against the actual years:或 plot 对照实际年份:

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

which gives:这使:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM