Year over year matplotlib with legend

柔情痞子 提交于 2019-12-12 05:19:37

问题


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

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

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:

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.

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?


回答1:


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


来源:https://stackoverflow.com/questions/35543650/year-over-year-matplotlib-with-legend

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!