Matplotlib:绘制离散值

Ark*_*avo 5 python data-visualization matplotlib

我正在尝试绘制以下内容!

from numpy import *
from pylab import *
import random

for x in range(1,500):
    y = random.randint(1,25000)
    print(x,y)   
    plot(x,y)

show()
Run Code Online (Sandbox Code Playgroud)

但是,我一直得到一个空白图表(?)。为了确保程序逻辑正确,我添加了代码print(x,y),只是确认正在生成 (x,y) 对。

(x,y) 对正在生成,但没有情节,我一直得到一个空白图。

有什么帮助吗?

Dan*_*l G 5

首先,有时我通过这样做取得了更好的成功

from matplotlib import pyplot
Run Code Online (Sandbox Code Playgroud)

而不是使用 pylab,尽管在这种情况下这应该不会产生影响。

我认为您的实际问题可能是正在绘制点但不可见。使用列表一次性绘制所有点可能效果更好:

xPoints = []
yPoints = []
for x in range(1,500):
    y = random.randint(1,25000)
    xPoints.append(x)
    yPoints.append(y)
pyplot.plot(xPoints, yPoints)
pyplot.show()
Run Code Online (Sandbox Code Playgroud)

为了使其更加简洁,您可以使用生成器表达式:

xPoints = range(1,500)
yPoints = [random.randint(1,25000) for _ in range(1,500)]
pyplot.plot(xPoints, yPoints)
pyplot.show()
Run Code Online (Sandbox Code Playgroud)

  • +1“导入 pyplot”——显然对于那些以前的 Matlab 用户来说,pylab 非常方便,但是在文档、示例等中这两种方言几乎可以互换使用,这使得 Matplotlib 尽管很出色,但使用起来却困难得多我来学习。 (3认同)