Year over year matplotlib with legend
Question: I'm trying to mimic this graph from Excel [![enter image description
here](http://i.stack.imgur.com/P2WLQ.png)](http://i.stack.imgur.com/P2WLQ.png)
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: [![enter image
description
here](http://i.stack.imgur.com/oonbr.png)](http://i.stack.imgur.com/oonbr.png)

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?


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

[![Example
Plot](http://i.stack.imgur.com/Hsqt9.png)](http://i.stack.imgur.com/Hsqt9.png)

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

