在matplotlib中切换图形对象 - 更改活动图形

问题描述 投票:1回答:2

假设我们正在创建两个我们需要在循环中填写的数字。这是一个玩具示例(不起作用):

import matplotlib.pyplot as plt
import numpy as np

fig,ax = plt.subplots(2,2)
fig1,ax1 = plt.subplots(2,2)

for i in np.arange(4):
    ax = plt.subplot(2, 2, i+1)
    sns.distplot(np.random.normal(0,1,[1,100]), ax=ax)
    ax1 = plt.subplot(2, 2, i+1)
    sns.distplot(np.random.normal(-1,1,[1,100]),color='r', ax=ax1)

这不起作用,因为ax = plt.subplot(25, 4, i+1)将简单地引用当前活动的最后一个图形(图1),而ax1 = plt.subplot(25, 4, i+1)将简单地创建指向相同位置的另一个对象,这将导致在同一位置生成两个图。 那么,我该如何更改活动数字呢? 我看了看这个question,但没有设法使它适用于我的情况。

电流输出

代码导致空fig

fig

并且它描绘了fig1中的所有内容

fig1

期望的输出

这是它应该如何表现:

fig

fig2

fig1

fig3

python matplotlib figure
2个回答
3
投票

我会用flatten

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

fig,ax = plt.subplots(2,2)
ax = ax.flatten()
fig1,ax1 = plt.subplots(2,2)
ax1 = ax1.flatten()

for i in np.arange(4):
    sns.distplot(np.random.normal(0,1,[1,100]), ax=ax[i])
    sns.distplot(np.random.normal(-1,1,[1,100]),color='r', ax=ax1[i])

1
投票

几个指针:

  1. 您已经分别在ax和ax1中定义了一个2x2轴。你不需要在循环内再次制作子图。
  2. 您可以简单地展平2X2阵列并将其作为数组进行迭代。
  3. 在将它们展平为sns.distplot作为轴(ax = flat_ax [i] OR ax = flat_ax1 [i])之后,可以添加相应的轴(ax或ax1)
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

fig,ax = plt.subplots(2,2)
fig1,ax1 = plt.subplots(2,2)

#Flatten the n-dim array of ax and ax1
flat_ax = np.ravel(ax)
flat_ax1 = np.ravel(ax1)

#Iterate over them
for i in np.arange(4):
    sns.distplot(np.random.normal(0,1,[1,100]), ax=flat_ax[i])
    sns.distplot(np.random.normal(-1,1,[1,100]),color='r', ax=flat_ax1[i])
© www.soinside.com 2019 - 2024. All rights reserved.