如何添加子图

How to add a subplot

如何将图表添加为 subplot

我可以 plot 独立 graph。但我想将其添加为 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()

请查看下面的输出。我可以将 subplot 添加到 One Plot,但 Two Plot 中的 bar chart 会作为独立图表生成。我想将它添加到 Two Plot.

这个例子只显示 2 subplots。我的实际代码有 8 个。虽然有更简单的方法可以实现上述解决方案,但我确实需要使用这种技术。

如果我尝试将 bar chart 分配给 Plot Two,我会得到一个错误: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

我不确定我是否正确解释了问题...

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

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

df = pd.DataFrame(data=d)

fig, (ax1, ax2, ax3) = plt.subplots(1,3, figsize=(13,5))
sns.countplot(x = df.C, ax = ax1)
sns.countplot(x = df.B, ax = ax2)
sns.countplot(x = df.C, hue =df.B,  ax = ax3)

在这里找到答案:

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