如何将子图添加到一组图

如何将子图添加到一组图

本文介绍了如何将子图添加到一组图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组要显示为subplotsplots.我可以添加大多数,但是我很难添加一个特定的.对于下面的代码,我可以为Plot OnePlot Three添加subplot,但是不能将子图添加到Plot Two.没有错误,但是将其作为单独的figure产生.

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.

如果我尝试将条形图分配给ax2,则会收到错误消息:SyntaxError: can't assign to function call

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

推荐答案

您快到了.只是将代码最后一部分的括号放错了位置.

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

尝试:

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)

这篇关于如何将子图添加到一组图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 04:55