0

I want to plot a sin-function and show it, then add a cos-function and plot again, so that the output is two plots, the first with only sin and the second with sin AND cos. But show() flushes the plot, how do I prevent the flushing?

import numpy as np
import matplotlib.pyplot as plt

f1 = lambda x: np.sin(x)
f2 = lambda x: np.cos(x)
x = np.linspace(1,7,100)
y1 = f1(x)
y2 = f2(x)

plt.plot(x,y1)
plt.show() #can I avoid flushing here?

plt.plot(x,y2)
plt.show()

I need it in a jupyter notebook.

2
  • You have two plt.show() because you want two plots right? Do they have to be in the same notebook cell? You could bypass the problem by plotting them from different cells: cell 1: plt.plot(x,y1) plt.show() cell2: plt.plot(x,y1) plt.plot(x,y2) plt.show() If you don't want two plots you have to use subplots: matplotlib.org/devdocs/api/_as_gen/… Commented Nov 13, 2017 at 12:54
  • Is the aim to have 2 figures as output or to have one figure which changes its content? Commented Nov 13, 2017 at 13:23

2 Answers 2

1

Would recommend doing it in the Object Oriented way.

%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
import time
f1 = lambda x: np.sin(x)
f2 = lambda x: np.cos(x)
x = np.linspace(1,7,100)
y1 = f1(x)
y2 = f2(x)

f,ax = plt.subplots() # creating the plot and saving the reference in f and ax

ax.plot(x,y1)
f.canvas.draw()
time.sleep(1) # delay for when to add the second line
ax.plot(x,y2)
f.canvas.draw()

Edit: Noticed you need it in jupyter notebook and the first solution i posted didn't work there, but the one posted now does. Use f.canvas.draw() instead of plt.show().

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

2 Comments

Why not just f1 = np.sin?
@chthonicdaemon Sure, but the focus of this question was the plotting part.
0

Use subplot i.e.

import numpy as np
import matplotlib.pyplot as plt

f1 = lambda x: np.sin(x)
f2 = lambda x: np.cos(x)
x = np.linspace(1,7,100)
y1 = f1(x)
y2 = f2(x)
#define 2-plots vertically, 1-plot horizontally, and select 1st plot
plt.subplot(2,1,1)
plt.plot(x,y1)

#As above but select 2nd plot
plt.subplot(2,1,2)
#plot both functions
plt.plot(x,y1)
plt.plot(x,y2)
#show only once for all plots
plt.show()

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.