假设我们正在创建两个需要在循环中填充的图形。 这是一个玩具示例(不起作用):
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)
将仅引用当前处于事件状态的最后一个创建的图形 (fig1),并且 ax1 = plt.subplot(25, 4, i+1)
将简单地创建另一个引用同一位置的对象,这将导致在同一位置生成两个图。
那么,如何更改事件人物呢?
我看了这个question但没能让它适用于我的情况。
当前输出
代码结果是一个空的fig
它绘制了fig1
中的所有内容
期望的输出
它应该是这样的:
图
图1
最佳答案
我会使用展平
:
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])
关于python - 在 matplotlib 中的图形对象之间切换 - 更改事件图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55495224/