'Plotting pivot table results from two groups into subplots in Python
I have created a pivot table with pd.pivot_table with two columns loc and sub resulting in the following table:
#example data
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'times': ['2019', '2020', '2019', '2020', '2019', '2020', '2019', '2020'],
'values': [0, 5, 10, 15, 3, 5, 10, 15],
'sub': ['N', 'N', 'P', 'P', 'N', 'N', 'P', 'P'],
'loc': ['1', '2', '1', '2', '1', '2', '1', '2']})
Now I want to make subplots for all uniques of loc separately but with all the sub uniques in the same subplot.
Using this code results in 2 columns for the sub uniques with the number of rows as loc uniques:
subs = ['N', 'P']
locs = ['1', '2']
pd.pivot_table(df.reset_index(),
index='times', columns=['loc', 'sub'], values='values'
).plot(subplots=True, kind='area', grid=True, legend=True, stacked=False, sharex=True,
layout=(len(locs), len(subs)))
Example results
This is the current plot result with all instances separated into subplots:

The ultimate goal is to merge the different sub columns.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|


