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.
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().
Use subplot ie
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.