[英]matplotlib: drawing simultaneously to different plots
Due to the 2nd answer of this question I supposed the following code 由于这个问题的第二个答案,我假设以下代码
import matplotlib.pyplot as plt
for i1 in range(2):
plt.figure(1)
f, ax = plt.subplots()
plt.plot((0,3), (2, 2), 'b')
for i2 in range(2):
plt.figure(2)
f, ax = plt.subplots()
plt.plot([1,2,3], [1,2,3], 'r')
plt.savefig('foo_{}_bar_{}.jpg'.format(i2, i1))
plt.close()
plt.figure(1)
plt.plot( [1,2,3],[1,2,3], 'r')
plt.savefig('bar_{}.jpg'.format(i1))
plt.close()
to create plots bar_0.jpg
and bar_1.jpg
showing a blue and a red line each. 创建图
bar_0.jpg
和bar_1.jpg
显示一条蓝线和一条红线。
However, figures look like 但是,数字看起来像
instead of 代替
How can I achieve the desired behaviour? 我怎样才能达到预期的行为? Note that plots
foo_*.jpg
have to be closed and saved during handling of the bar
plots. 请注意,在处理
bar
,必须关闭并保存图foo_*.jpg
。
You're already saving the Axes
objects, so instead of calling the PyPlot plot
function (which draws on the last created or activated Axes
), use the objects' plot
function: 您已经保存了
Axes
对象,因此,不要调用PyPlot plot
函数(该函数在最后创建或激活的Axes
上进行绘制),而是使用对象的plot
函数:
ax.plot(...)
If you then give both a different name, say ax1
and ax2
, you can draw on the one you like without interfering with the other. 如果然后给两个不同的名称,例如
ax1
和ax2
,则可以使用您喜欢的一个,而不会干扰另一个。 All plt.
全部
plt.
commands also exist as an Axes
member function, but sometimes the name changes ( plt.xticks
becomes ax.set_xticks
for example). 命令也作为
Axes
成员函数存在,但有时名称会更改(例如plt.xticks
变为ax.set_xticks
)。 See the documentation of Axes
for details. 有关详细信息,请参见
Axes
的文档 。
To save to figures, use the Figure
objects in the same way: 要保存为图形,请以相同方式使用
Figure
对象:
f.savefig(...)
This API type is only just coming to Matlab, FYI, and will probably replace the old-fashioned "draw on the last active plot" behaviour in the future. 该API类型仅在FYI的Matlab上推出,将来可能会取代老式的“在最后一个活动地块上绘制”行为。 The object-oriented approach here is more flexible with minimal overhead, so I strongly recommend you use it everywhere.
这里的面向对象方法更加灵活,开销最小,因此我强烈建议您在任何地方使用它。
If unsure, better to make it explicit: 如果不确定,最好使其明确:
import matplotlib.pyplot as plt
for i1 in range(2):
fig1,ax1 = plt.subplots()
fig2,ax2 = plt.subplots()
ax1.plot([0,4],[2,2],'b')
for i2 in range(2):
ax2.plot([1,2,3],[1,2,3],'r')
fig2.savefig('abc{}.png'.format(2*i1+i2))
plt.figure(1)
ax1.plot([1,2,3],[1,2,3],'r')
fig1.savefig('cba{}.png'.format(i1))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.