Matplotlib:使用与先前轴相同的参数添加轴 [英] Matplotlib: Adding an axes using the same arguments as a previous axes
问题描述
我想在两个不同的子图中绘制数据.绘制后,我想回到第一个子图并在其中绘制另一个数据集.但是,当我这样做时,会收到以下警告:
I want to plot data, in two different subplots. After plotting, I want to go back to the first subplot and plot an additional dataset in it. However, when I do so I get this warning:
MatplotlibDeprecationWarning:当前使用与以前的轴相同的参数添加轴现在会重用较早的实例.在将来的版本中,将始终创建并返回一个新实例.同时,通过向每个轴实例传递唯一的标签,可以抑制此警告,并确保将来的行为. warnings.warn(消息,mplDeprecation,stacklevel = 1)
MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance. In a future version, a new instance will always be created and returned. Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance. warnings.warn(message, mplDeprecation, stacklevel=1)
我可以用一段简单的代码来重现它:
I can reproduce that with a simple piece of code:
import matplotlib.pyplot as plt
import numpy as np
# Generate random data
data = np.random.rand(100)
# Plot in different subplots
plt.figure()
plt.subplot(1, 2, 1)
plt.plot(data)
plt.subplot(1, 2, 2)
plt.plot(data)
plt.subplot(1, 2, 1) # Warning occurs here
plt.plot(data + 1)
关于如何避免此警告的任何想法?我使用matplotlib 2.1.0.看起来与此处
Any ideas on how to avoid this warning? I use matplotlib 2.1.0. Looks like the same problem as here
推荐答案
This is a good example that shows the benefit of using matplotlib
's object oriented API.
import numpy as np
import matplotlib.pyplot as plt
# Generate random data
data = np.random.rand(100)
# Plot in different subplots
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.plot(data)
ax2.plot(data)
ax1.plot(data+1)
plt.show()
注意:以变体名称开头的小写字母(例如, data = ...
而不是Data = ...
参见 PEP8
Note: it is more pythonic to have variable names start with a lower case letter e.g. data = ...
rather than Data = ...
see PEP8
这篇关于Matplotlib:使用与先前轴相同的参数添加轴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!