2

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. 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.

But instead I get the first two plots and a plot with just sin(x) and plot with just sin(x+pi).

How do I get all the data I want on to figure 2? It seems to be some sort of issue with the set figure resetting when I return to the beginning of the loop.

7
  • 1
    Don't call plt.show() after each call to plt.plot(), but rather only once after you've made all your calls to plt.plot(). Commented Feb 8, 2018 at 0:02
  • 1
    Would you mind providing a minimal reproducible example with real code in your question, such that people can understand and reproduce what you are doing? Also clearly state the desired output. "a plot for figure 1" is not really understandable. Rather say which data you'd expect to appear on which figure. Commented Feb 8, 2018 at 0:06
  • @cmaher To clarify my understanding of what I wrote (which may be incorrect): first time through the loop I plot and display figure 1 and then plot , but don't display figure 2. The next time through the loop, I again plot and display a figure 1 with new data and plot another set of data to figure 2, but don't plot. Then after leaving the loop, I try to display figure 2. To me, that seems like I'm calling plt.show() only after I have plotted all my data. Commented Feb 8, 2018 at 0:09
  • @ImportanceOfBeingErnest I will edit the code and question accordingly. Commented Feb 8, 2018 at 0:10
  • @ImportanceOfBeingErnest is this fleshed out enough? I believe this is verifiable and seems to cover the crux of my problem. Commented Feb 8, 2018 at 3:49

1 Answer 1

2

This minimal change will probably do what you want (although it is not the best code).

Replace plt.figure(1) with plt.figure(). Remove any plt.show() from inside the loop.

The loop will end and then all 3 figures will be shown. The e^x curves will be in figures #1 and #3.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.