一年一度的matplotlib与图例 [英] Year over year matplotlib with legend

查看:63
本文介绍了一年一度的matplotlib与图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Excel模仿此图.

I'm trying to mimic this graph from Excel in python and matplotlib.

下面显示的数据框(by_year)的多重索引为编辑-更改表以反映行不同

The dataframe (by_year) looks below with a multiindex of EDIT - Changed table to reflect that the rows are different

Month 1   2   3   4   5   6   7   8   9   10   11   12
Year
2012  8   6   8   9   1   2   8   9   4   3    2    6
2013  5   6   2   9   6   2   8   9   4   3    2    6
2014  7   6   3   9   4   2   8   9   4   3    2    6

# create multiple plots on the page (i'm going to print this rather
# than display live
ax1 = plt.subplot2grid((3, 2), (0,0), colspan=2)
ax2 = plt.subplot2grid((3, 2), (1,0))

# loop through the years (each row) and add to chart
for idx, row in by_year.iterrows():
    row_values = row.values.astype(int).tolist()
    ax1.bar(month_list, row_values)
    ax1.legend(str(idx))

问题1-运行没有错误,但是我只得到一组标尺.不知道如何解决此问题.图看起来像这样:

Problem 1 - This runs with no errors, however i only get a single set of bars. Don't understand how to fix this. Graph looks like this:

编辑-问题在ax1.bar(month_list ...行中.它对每行使用相同的起点,因此条形图彼此重叠.@ GWW的以下解决方案使用idx.我真的会把它命名为bar_start.

EDIT - Problem is in the ax1.bar(month_list... line. It uses the same starting point for each row and hence the bars are on top of each other. The solution below by @GWW calculates the start position using idx. Which i would really name bar_start.

问题2-我在任何地方都找不到如何在表格下添加带有图例的图例.我可以尝试通过简单地显示数据框来创建(我认为:)),但是Matplotlib是否已经具有该功能?

Problem 2 - I can't find anywhere how to add that legend with the data under the table. I can try and create by simply displaying the dataframe (i think :) ) but does Matplotlib already have the functionality?

推荐答案

这应该可以帮助您入门.您仍将不得不摆弄表格属性以使其看起来更好.

This should get you started. You will still have to fiddle around with the table properties to make it look better.

months = [1,2,3,4,5,6,7,8,9,10,11,12]

by_year = [
(2012,  (8,6,8,9,1,2,8,9,4,3,2,6)),
(2013,  (5,6,2,9,6,2,8,9,4,3,2,6)),
(2014,  (7,6,3,9,4,2,8,9,4,3,2,6)),
]

colors = ['r','g','b','y']
import pylab as plt
fig, ax = plt.subplots(1,1, figsize=(8, 4))

#0.9  to leave a small space between groups of bars
import numpy as NP
N = 0.95 / (len(by_year))

cell_text = []
for i, (year, row) in enumerate(by_year):
    print i, year, row
    idx = NP.arange(0, len(months)) + N * i
    # * 0.8 to put a small gap between bars
    ax.bar(idx, row, color=colors[i], width=N * 0.8, label=year)
    cell_text.append(row)

tbl = ax.table(cellText=cell_text, rowLabels=[x[0] for x in by_year], loc='bottom', colLabels=months)
prop = tbl.properties()
ax.set_xticks([])
lgd = ax.legend(loc='upper left', bbox_to_anchor=(1, 1.0))
fig.show()

这篇关于一年一度的matplotlib与图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆