假设我们正在创建两个我们需要在循环中填写的数字。这是一个玩具示例(不起作用):
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
并且它描绘了fig1
中的所有内容
这是它应该如何表现:
fig
fig1
我会用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])
几个指针:
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])