Matplotlib:绘制离散值

5 投票
1 回答
36947 浏览
提问于 2025-04-15 21:19

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

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

但是,我总是得到一张空白的图表(?)。为了确保程序的逻辑是正确的,我添加了代码 print(x,y),只是为了确认 (x,y) 的数据对确实被生成了。

虽然 (x,y) 的数据对确实生成了,但图表却没有显示出来,我一直得到的是一张空白的图。

有人能帮帮我吗?

1 个回答

5

首先,有时候我发现用下面这种方式效果更好:

from matplotlib import pyplot

而不是使用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()

为了让这个更整洁,你还可以使用生成器表达式:

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

撰写回答