如何添加子图

时间:2018-06-29 05:37:19

标签: python pandas matplotlib assign 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,但是bar chart中的Two Plot会作为独立图形生成。我想将其添加到Two Plot

此示例仅显示2 subplots。我的实际代码为8。尽管有更简单的方法来实现上述解决方案,但我确实需要使用此技术。

enter image description here 如果我尝试将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

2 个答案:

答案 0 :(得分:1)

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

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)

enter image description here

答案 1 :(得分:0)

在这里找到答案

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