2017-11-13 1 views
0

Ich möchte eine sin-Funktion plotten und zeigen, dann fügen Sie eine cos-Funktion und plotten wieder, so dass die Ausgabe zwei Plots ist, die erste mit nur Sünde und die zweite mit Sünde UND cos. Aber show() löscht die Handlung, wie verhindere ich die Spülung?Fügen Sie Linien zum Plotten in pyplot hinzu

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() 

Ich brauche es in einem jupyter Notebook.

+0

Sie haben zwei plt.show(), weil Sie zwei Parzellen wollen nicht wahr? Müssen sie in derselben Notebookzelle sein? Sie könnten das Problem umgehen, indem sie aus verschiedenen Zellen Plotten: Zelle 1: plt.plot (x, y 1) plt.show() cell2: plt.plot (x, y 1) plt.plot (x, y 2) plt.show() Wenn Sie nicht über zwei Parzellen wollen, müssen Nebenhandlungen verwenden: https://matplotlib.org/devdocs/api/_as_gen/matplotlib.pyplot.subplots.html – Djib2011

+0

Ist das Ziel, 2 Zahlen als Ausgabe zu haben oder eine Zahl zu haben, die ihren Inhalt ändert? – ImportanceOfBeingErnest

Antwort

1

Ich würde es auf objektorientierte Weise empfehlen.

%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: Sie in jupyter Notebook benötigen sie Bemerkt und die erste Lösung, die ich nicht dort gebucht funktionierte, aber die man jetzt tut gebucht. Verwenden Sie f.canvas.draw() anstelle von plt.show().

+0

Warum nicht einfach 'f1 = np.sin'? – chthonicdaemon

+0

@chtonicdaemon Sicher, aber der Schwerpunkt dieser Frage war der Plotteil. –

0

Verwenden subplot heißt

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() 
Verwandte Themen