Search code examples
pythonpandasmatplotlibassignsubplot

How to add a subplot


How can you add a graph as a subplot.

I can plot a stand alone graph. But I would like to add this as a subplot.

import pandas as pd
import matplotlib.pyplot as plt

d = ({
    'A' : ['1','1','1','2','2','2','3','3','3','3'],     
    'B' : ['A','B','C','A','B','C','D','A','B','C'],
    'C' : ['John','Carl','Carl','John','Lily','John','Lily','John','Carl','Carl'],  
    'D' : [1,2,3,4,5,6,7,8,9,10], 
    'E' : [0,2,4,6,5,6,7,8,9,10],          
    })

df = pd.DataFrame(data=d)

fig = plt.figure(figsize = (9,4))

def One_plot(ax,pid, fontsize=12):
    ax.set_title('One Plot', fontsize=10)
    ax.scatter(df['E'],df['D'])
    ax.grid(False)

def Two_plot(ax,pid):
    df.assign(A=df.A.astype(int)).pivot_table(index="C", columns="B", values="A",aggfunc='count').rename_axis(None).rename_axis(None,1).plot(kind='bar')
    ax.set_title('Two Plot', fontsize=10)

ax1 = plt.subplot2grid((3,3), (0, 0), colspan = 3)
ax2 = plt.subplot2grid((3,3), (1, 0), colspan = 2)

One_plot(ax1,1)
Two_plot(ax2,1)

fig.tight_layout()

Please see output below. I can add the subplot to One Plot but the bar chart in Two Plot gets produced as a stand alone graph. I would like to add it to Two Plot.

This example only displays 2 subplots. My actual code has 8. Whilst there are easier ways to achieve the above solution, I do need to use this technique.

enter image description here If I try assign the bar chart to Plot Two I get an error: SyntaxError: can't assign to function call

df.assign(A=df.A.astype(int)).pivot_table(index="C", columns="B", values="A",aggfunc='count').rename_axis(None).rename_axis(None,1).plot(kind='bar'),

df.assign(A=df.A.astype(int)).pivot_table(index="C", columns="B", values="A",aggfunc='count').rename_axis(None).rename_axis(None,1).plot(kind='bar'), 
ax = ax2# Error

Solution

  • Answer found here:

    How to add a subplot to a group of plots

    df.assign(A=df.A.astype(int)).pivot_table(index="C", columns="B", values="A",aggfunc='count').rename_axis(None).rename_axis(None,1).plot(kind='bar', ax = ax2),