如何在python中绘制平均数据直方图?

时间:2016-04-18 15:02:47

标签: python matplotlib histogram

我有一个看起来像这样的直方图: enter image description here

你看,每年(X)有几个Y,所以直方图有重叠的条形。 我怎样才能建立最大Y?并为平均?

我的代码是:

  My dataframe is:
    Data  Amount
    1996    65155
    1984    88705
    1996    115551
    2010    87222
    1995    3043
    1994    54789
    2007    87655
    1996    55189
    2005    34914
    2005    122643
    1995    111700
    1996    64065
    1995    76783
    1994    85687
    1995    88515
    1996    48352
    1995    315025
    1995    80074
    1995    133998
    2000    40918
    2000    108585
    1996    119506
    2003    105385
    2003    93374
    1996    63970
    1995    15261
    1996    128078
    1995    83593
    1994    54544
    2006    108167
    1996    141421
    2005    83725

year=df[['Year']].as_matrix()
amount=df[['Amount']].as_matrix()

stepsize = 10
fig, ax = plt.subplots()
ax.bar(year, amount, width=1)
start, end = ax.get_xlim()
ax.set_xlabel('Year')
ax.set_ylabel('Amount')
ax.set_title(r'Amount - year')
ax.xaxis.set_ticks(np.arange(start, end, stepsize))
plt.show()

1 个答案:

答案 0 :(得分:0)

由于您使用pandas读取数据,因此您可以使用数据框对数据进行分组,根据需要进行聚合,并绘制这些值。我在下面的示例中使用了max值,但您也可以使用meanmin,......等等。

另请注意我如何使用StringIO使此示例完全复制/粘贴。

from io import StringIO
import pandas

datafile = StringIO("""\
Year  Amount
1996    65155
1984    88705
1996    115551
2010    87222
1995    3043
1994    54789
2007    87655
1996    55189
2005    34914
2005    122643
1995    111700
1996    64065
1995    76783
1994    85687
1995    88515
1996    48352
1995    315025
1995    80074
1995    133998
2000    40918
2000    108585
1996    119506
2003    105385
2003    93374
1996    63970
1995    15261
1996    128078
1995    83593
1994    54544
2006    108167
1996    141421
2005    83725
""")

df = pandas.read_csv(datafile, sep='\s+')
ax = df.groupby(by=['Year']).max().plot.bar(legend=False)
ax.set_ylabel("Amount")

enter image description here