【问题标题】:How to add a subplot to a group of plots如何将子图添加到一组图
【发布时间】:2018-12-14 14:13:36
【问题描述】:

我有一组plots,我想显示为subplots。我可以添加其中的大部分,但我正在努力添加一个特定的。对于下面的代码,我可以为Plot OnePlot Three 添加subplot,但我不能将子图添加到Plot Two。没有错误,但它会生成为单独的 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()

这是当前的输出。如您所见,我想放置在第二个情节中的条形图被生成为一个单独的图形。

如果我尝试将条形图分配给 ax2,则会出现错误: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

【问题讨论】:

    标签: python pandas matplotlib subplot


    【解决方案1】:

    你快到了。只是代码最后一部分的括号放错了位置。

    试试:

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多