2017-08-30 140 views
0

plt.show(),顯示一個窗口,但它沒有曲線。Matplotlib不繪製曲線

我的代碼:

In [1]: import math 

In [2]: import numpy as np 

In [3]: import matplotlib.pyplot as plt 

In [4]: Lm=0 

In [5]: for angle in np.arange(0.0,90.0,0.1): 

    ...:  theta = angle*math.pi/180 

    ...:  L=0.25*(math.cos(theta))*(5*math.sin(theta)+math.sqrt(25*math.sin(theta)*math.sin(theta)+80)) 

    ...:  print(L,"\t",angle) 

    ...:  if L>Lm: 

    ...:   Lm=L 

    ...: 


In [6]: plt.figure(1) 

Out[6]: <matplotlib.figure.Figure at 0x284e5014208> 

In [7]: for angle in np.arange(0.0,90.0,0.1): 

    ...:  celta = angle*math.pi/180 

    ...:  L=0.25*(math.cos(theta))*(5*math.sin(theta)+math.sqrt(25*math.sin(theta)*math.sin(theta)+80)) 

    ...:  plt.figure(1) 

    ...:  plt.plot(angle,L) 

    ...: 

In [8]: plt.show() 

輸出

enter image description here

+0

隨着'plt.plot'的每次調用,一個'Lines'對象被添加到'Figure'實例。一個'Lines'對象試圖按順序給出的點之間的線(線性插值)。現在問題在於要創建一條線需要至少兩個點,但每次調用'plt.plot'時,都會創建一個只有一個點的線條對象。這就是爲什麼你什麼都看不到。使用NumPy的通用函數'sin'和'cos'來代替它們,讓它們與數組一起工作。 – Michael

回答

1

從我所看到的,L第二計算是完全一樣的第一個(除了你總是使用相同的值theta,我想這不是你想要在第二個循環中實現的) 。你也根本不使用celta。我們只是將它踢出去。根本沒有使用Lm,所以我也要去解決這個問題,但是從我看到的結果你可以計算出Lm之後的np.max(L)

而剩下的就是下面的代碼:

import numpy as np 
import matplotlib.pyplot as plt 

angles = np.arange(0.0, 90.0, 0.1) 
theta = angles * np.pi/180 
L = 0.25 * np.cos(theta) * (5*np.sin(theta) + 
          np.sqrt(25*np.sin(theta)*np.sin(theta) + 80)) 
plt.plot(angles, L) 
plt.show() 

現在,你有plt.plot只有一個呼叫與一分不少的創建Lines例如,你可以看到一個情節。

+0

非常感謝。你真的糾正了我的錯誤,並告訴我方便的方法。 –