0

I have a group of plots that I want to display as subplots. I can add most of them but I'm struggling to add a particular one. For the code below I can add the subplot for Plot One and Plot Three but I can't add the subplot to Plot Two. There's no error but it gets produced as a separate figure.

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],          
})

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

df = pd.DataFrame(data=d)

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

def Plot_Two(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('Plot Two', fontsize=10)

def Plot_Three(ax,pid, fontsize=12):
    ax.set_title('Plot Three', fontsize=10)
    ax.plot(df['E'],df['D'])

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

Plot_One(ax1,1)
Plot_Two(ax2,1) 
Plot_Three(ax3,1)

fig.tight_layout()

This is the current output. As you can see the bar chart that I want to place in Plot Two gets produced as a separate figure.

enter image description here If I try assign the bar chart to ax2 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'), ax = ax2

1 Answers1

0

You are almost there. Simply the bracket of the last part of your code is misplaced.

Try:

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)
gyoza
  • 2,112
  • 2
  • 12
  • 18