Subplot multiple combination of categories in python

Question:

I have the following example dataset where ‘Type1 has 2 categories ‘A’ and ‘B’ and ‘Type2’ has 3 categories ‘Red’, ‘Blue’, and ‘ Green’. I would like to plot 3 subplots where subplot 1 has ‘Type1’, subplot 2 has ‘Type2’ and subplot3 has the combination of ‘Type1’ and ‘Type2’. The x axis is the ‘Time’ and the y axis is the ‘Amount’. The combination subplot should be at the bottom of the first 2 subplot. And the subplot should be lineplot.

Time, Type1, Type2, Amount 
0, A, Red, 1000
1, A, Red, 1002
2, A, Red, 1003
0, B, Blue, 50
1, B, Blue, 54
2, B, Blue, 60
0, A, Green, 89
1, A, Green, 90
2, A, Green, 100

I did not find anything useful in this regard. Any help is appreciated.
Note: A resulting subplot should look like the answer in the subplot 3 graphs matplotlib

Asked By: non_linear

||

Answers:

IIUC:

import matplotlib.pyplot as plt

fig = plt.figure(constrained_layout=True, figsize=(8, 8))
gs = fig.add_gridspec(2, 2)

ax1 = fig.add_subplot(gs[0, 0])
df.groupby(['Time', 'Type1'])['Amount'].mean().unstack('Type1').plot(ax=ax1)

ax2 = fig.add_subplot(gs[0, 1])
df.groupby(['Time', 'Type2'])['Amount'].mean().unstack('Type2').plot(ax=ax2)

ax3 = fig.add_subplot(gs[1, :])
df.groupby(['Time', 'Type1', 'Type2'])['Amount'].mean().unstack(['Type1', 'Type2']).plot(ax=ax3)

plt.show()

Output:

enter image description here

Note: groupby_unstack can be replaced by pivot_table:

>>> df.groupby(['Time', 'Type1', 'Type2'])['Amount'].mean().unstack(['Type1', 'Type2'])

Type1      A             B
Type2  Green     Red  Blue
Time                      
0       89.0  1000.0  50.0
1       90.0  1002.0  54.0
2      100.0  1003.0  60.0

>>> df.pivot_table(index='Time', columns=['Type1', 'Type2'], 
                   values='Amount', aggfunc='mean')
Type1     A          B
Type2 Green   Red Blue
Time                  
0        89  1000   50
1        90  1002   54
2       100  1003   60
Answered By: Corralien
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.