简体   繁体   English

Matplotlib:在旧图上绘图

[英]Matplotlib: plotting on old plot

After review this question ( How do I tell Matplotlib to create a second (new) plot, then later plot on the old one? ) I thought I had figured this out, but I think I'm running into an issue with my for loops.查看这个问题后(如何告诉 Matplotlib 创建第二个(新)图,然后在旧图上绘制? )我以为我已经解决了这个问题,但我想我的 for 循环遇到了问题. Here is a pared down version of what I'm doing.这是我正在做的事情的精简版。

import matplotlib.pyplot as plt
import numpy as np

for m in range(2):
   x=np.arange(5)
   y=np.exp(m*x)
   plt.figure(1)
   plt.plot(x, y)
   plt.show()
   ...
   z=np.sin(x+(m*math.pi))
   plt.figure(2)
   plt.plot(x,z)
   ...
plt.figure(2)
plt.show()

My hope was that this would display three plots: a plot for e^(0) vs x the first time through, a plot of e^x vs x the second time through, and then one plot with both sin(x) and sin(x+pi) vs x.我希望这会显示三个图:第一次通过 e^(0) 与 x 的图,第二次通过 e^x 与 x 的图,然后是一个同时包含 sin(x) 和 sin 的图(x+pi) 与 x。

But instead I get the first two plots and a plot with just sin(x) and plot with just sin(x+pi).但相反,我得到了前两个图和一个只有 sin(x) 的图和只有 sin(x+pi) 的图。

How do I get all the data I want on to figure 2?我如何获得我想要的所有数据到图 2? It seems to be some sort of issue with the set figure resetting when I return to the beginning of the loop.当我返回到循环的开头时,设置数字重置似乎存在某种问题。

This minimal change will probably do what you want (although it is not the best code).这个最小的更改可能会做你想要的(虽然它不是最好的代码)。

Replace plt.figure(1) with plt.figure() .plt.figure(1)替换为plt.figure() Remove any plt.show() from inside the loop.从循环内部删除任何plt.show()

The loop will end and then all 3 figures will be shown.循环将结束,然后将显示所有 3 个数字。 The e^x curves will be in figures #1 and #3. e^x曲线将在图#1 和#3 中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM