【问题标题】:Matplotlib does not plot curveMatplotlib 不绘制曲线
【发布时间】:2017-08-30 06:22:43
【问题描述】:

plt.show(),显示一个窗口,但上面没有曲线。

我的代码:

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

输出

【问题讨论】:

  • 每次调用plt.plot,都会将Lines 对象添加到Figure 实例中。 Lines 对象尝试在按顺序给定的点之间创建线(线性插值)。现在的问题是,要制作一条线,至少需要两个点,但每次调用 plt.plot 时,您都会创建一个只有一个点的 Lines 对象。这就是为什么你什么都看不到。改用 NumPy 的通用函数 sincos 并让它们与数组一起工作。

标签: python matplotlib anaconda


【解决方案1】:

据我所见,L 的第二次计算与第一次计算完全相同(除了您始终使用相同的 theta 值,我猜这不是您想要实现的第二个循环)。此外,您根本不使用celta。我们只是要把它踢出去。 Lm 根本不用,所以我也要把它踢掉,但据我所知,你可以在之后用 np.max(L) 计算 Lm

剩下的代码如下:

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 实例,您可以看到一个情节。

【讨论】:

  • 非常感谢。您确实纠正了我的错误并告诉了我方便的方法。
猜你喜欢
  • 2021-05-04
  • 1970-01-01
  • 2013-01-20
  • 1970-01-01
  • 2022-12-18
  • 1970-01-01
  • 2018-08-16
  • 2019-08-14
  • 1970-01-01
相关资源
最近更新 更多