Plot multiple subplots from a pivot table in Pandas

Viewed 284

I have the following df:

df = pd.DataFrame({
    'Year': np.repeat([2016, 2017], 4),
    'Period': np.tile([1, 1, 2, 2], 2),
    'Product': np.tile(['A', 'B'], 4),
    'Revenue': np.random.randint(1, 10, 8),
    })

df

    Year    Period  Product Revenue
0   2016       1       A       2 
1   2016       1       B       3
2   2016       2       A       7
3   2016       2       B       4
4   2017       1       A       8
5   2017       1       B       2
6   2017       2       A       9
7   2017       2       B       9

Based on that, I create a pivot table:

df = df.pivot_table(index=['Year', 'Period'],
                              columns='Product', values='Revenue',
                              aggfunc='sum')

        Product A   B
Year    Period      
2016    1   2   3
        2   7   4
2017    1   8   2
        2   9   9

I am looking for an elegant way to plot subplots for each year where period is in x-axis and products are separate lines.

I've been playing with pandas built-in plot method, but can't get this to work.

df.plot(subplots=True)

result of simple pandas plot with subplots param

I am aware that I could index the df, put it in a loop, and get all the plots one after another, like this:

for level in df.index.get_level_values(0).unique():
    df.loc[level, :].plot()

but I am wondering whether there is a more elegant way to do this.

0 Answers
Related