【问题标题】:Grouping of output plots from function函数的输出图分组
【发布时间】:2021-08-04 09:42:41
【问题描述】:

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

假设我有这个数据框:

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)

现在这会返回一系列条形图,一个在另一个之上。这不是很方便。我想要的是这些地块在一个网格中,比如一行 2 个地块。

我试过了:

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

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

我该如何解决这个问题?

【问题讨论】:

  • 此现有代码可以毫无问题地创建 3 个图(区域 1 - 3),每个图在 pandas 1.3.0matplotlib 3.4.2 中有 2 个子图(id 和 d)。这一切都可以通过ax = df.pivot(columns='zone', values=['id', 'd']).hist(figsize=(7, 10)) 在一行中完成。

标签: python pandas matplotlib plot seaborn


【解决方案1】:

你已经创建了一个你想要的网格,但是你还没有在任何地方使用它。

pandas.DataFrame.hist() 有一个参数 ax 为:

ax : Matplotlib 坐标轴对象,默认无

绘制直方图的坐标轴。

这段代码:

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

返回 Matplotlib 坐标轴对象 axs 的 Matplotlib 图 fignumpy.array(如果行或列为 1,则为 1 维,否则为 2 维)。

所以,你需要:

  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)

【讨论】:

  • 谢谢!这正是我想要的!
【解决方案2】:

你可以用循环来做:

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


或者seaborn.histplot:

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

【讨论】:

    猜你喜欢
    • 2011-01-29
    • 1970-01-01
    • 2021-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-12
    • 2017-07-28
    • 2011-11-18
    相关资源
    最近更新 更多