【问题标题】:Matplotlib: plotting discrete valuesMatplotlib:绘制离散值
【发布时间】:2011-02-05 03:42:05
【问题描述】:

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

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) 对正在生成,但没有绘图,我一直得到一个空白图表。

有什么帮助吗?

【问题讨论】:

  • Arkapravo,我对接受的答案没有任何问题;我只想提一下这个五行模板: from matplotlib import pyplot as PLT;图=PLT.图(); ax1=fig.add_subplot(111); ax1.plot(x, y); PLT.show() 是一种在 98% 的时间内获得有效 x-y 图的快速方法。 ('x', 'y' 是列表或一维 Numpy 数组,顺便说一句)。
  • @doug:你可以用更简单的方式做同样的事情:from matplotlib import pyplot at plt; plt.plot(x, y); plt.show()
  • @doug:谢谢! ...我接受了 Daniel G 的回答,因为它立即解决了我所有的问题! .... :) .. 太糟糕了 2 个答案无法选择!

标签: python matplotlib data-visualization


【解决方案1】:

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

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

【讨论】:

  • +1 for 'import pyplot'——显然对于那些以前的 Matlab 用户来说,pylab 是一个巨大的便利,但是这两种方言在文档、示例等中几乎可以互换使用,使得 Matplotlib,尽管它很出色,但我学习起来要困难得多。
  • 非常感谢伙计们!我想我最后一次涉足 matplotlib,有时是在 2009 年 10 月,某些需求出现了,我不得不在 2010 年 4 月回来。
  • yPoints = list(map(lambda: random.randint(1,25000), xPoints)) 并且不需要跟踪额外的变量。
猜你喜欢
  • 2015-12-26
  • 1970-01-01
  • 2016-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-23
  • 2018-10-31
  • 1970-01-01
相关资源
最近更新 更多