簡體   English   中英

在pyplot中添加線條以繪圖

[英]Add lines to plot in pyplot

我想繪制一個sin函數並顯示它,然后添加一個cos函數並再次繪制,以便輸出為兩個圖,第一個僅包含sin,第二個包含sin AND cos。 但是show()刷新圖,如何防止刷新?

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

我需要一本Jupyter筆記本。

建議以面向對象的方式進行操作。

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

編輯:注意到您在jupyter筆記本中需要它,而我發布的第一個解決方案在那兒不起作用,但現在發布的解決方案可以。 使用f.canvas.draw()代替plt.show()。

使用子圖

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM