函数输出图的分组

2024-04-29 07:48:08 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我今天一直在努力解决的问题。这是一个如何以这样的方式呈现数据的问题,以避免不得不在笔记本上向下滚动很长时间并失去比较图表的能力

假设我有这个数据帧:

id type zone    d
0    1    a   a1   23
1    1    a   b1   45
2    1    a   c1   23
3    2    a   c1   56
4    2    b   a1    7
5    2    b   b1    5
6    3    b   a1    2
7    3    b   a1    9
8    3    b   b1   43
9    4    c   c1   21
10   4    c   c1   67
11   5    c   b1   34
12   5    c   a1   21
13   1    a   a1    3
14   1    a   b1    4
15   1    a   c1   12
16   2    a   c1   10
17   2    b   a1   33
18   2    b   b1   22
19   3    b   a1  334
20   3    b   a1   22
21   3    b   b1   11
22   4    c   c1   55
23   4    c   c1   88
24   5    c   b1   22
25   5    c   a1    9

和下面的函数

def my_function(df,zone):
    df_new = df[df['zone']=="{}".format(zone)]
    df_new.hist()
    plt.suptitle("distances for zone {}".format(zone))

我为每个区域生成一个图形,执行以下操作

zoneList = list(set(df['zone'].unique()))

for zone in zoneList:
    my_function(df,zone)

现在返回一系列条形图,一个在另一个之上。这不太方便。我希望这些图是在一个网格中,比如说一行两个图

我试过这个:

fig, axs = plt.subplots(2, 2)
for zone in zoneList:
    axs = my_function(df,zone)

但它会返回我想要的网格,然后返回我之前得到的相同结果

我怎样才能解决这个问题


Tags: 数据informat网格zonedfnewfor
2条回答

您已经创建了所需的网格,但尚未在任何地方使用它

pandas.DataFrame.hist()有一个参数ax,如下所示:

ax : Matplotlib axes object, default None

The axes to plot the histogram on.

此代码:

fig, axs = plt.subplots(2, 2)

返回Matplotlib轴对象的Matplotlib图形fignumpy.array(如果行或列为1,则为一维,否则为二维)

因此,您需要:

  1. axs的展开版本上循环
  2. 将相应的ax对象传递给df_new.hist()方法

例如:

def my_function(df,zone,ax):
    df_new = df[df['zone']=="{}".format(zone)]
    df_new.hist(ax = ax)
    # set title just for this subplot
    ax.set_title("distances for zone {}".format(zone), loc = 'center')

fig, axs = plt.subplots(2, 2)
for zone, ax in zip(zoneList, axs.flatten()):
    my_function(df,zone,ax)

您可以通过循环来完成:

fig, ax = plt.subplots(1, 2)

for zone in df['zone'].unique():
    ax[0].hist(df[df['zone'] == zone]['d'], label = zone, bins = np.arange(df['d'].min(), df['d'].max() + 10, 10))
    ax[1].hist(df[df['zone'] == zone]['id'], label = zone, bins = np.arange(df['id'].min(), df['id'].max() + 0.5, 0.5))

ax[0].set_title('d')
ax[1].set_title('id')
ax[1].legend(frameon = True)

plt.show()

enter image description here


或与^{}一起:

fig, ax = plt.subplots(1, 2)

sns.histplot(ax = ax[0], data = df, x = 'd', hue = 'zone', binwidth = 10)
sns.histplot(ax = ax[1], data = df, x = 'id', hue = 'zone', binwidth = 0.5)

plt.show()

enter image description here

相关问题 更多 >