【问题标题】:Getting data into Matplot/pylab for scatter chart将数据输入 Matplot/pylab 用于散点图
【发布时间】:2020-04-27 14:25:32
【问题描述】:

我正在尝试创建一些数据的散点图。数据以列表列表中 x 和 y 坐标的形式出现。

stepsPlot = [[1, 0], [2, 0], [2, -1], [3, -1], [3, -2], [4, -2], [4, - 1], [4, 0], [4, -1], [5, -1]]

运行以下代码

import pylab as plt

plt.figure('Random Walk Scatter Plot')
plt.clf()
plt.title('Random Walk Scatter Plot')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.plot(stepsPlot)
plt.show()

生成一个排序图(用于测试)- 所以我知道它正在获取数据,但它不明白数据代表单个点。当我将 plt.plot(stepsPlots) 更改为 plt.scatter(stepsPlot) - 我从阅读文档中假设这是我需要的 - 我收到错误

TypeError: scatter() 缺少 1 个必需的位置参数:'y'

我假设这意味着 pylab 不理解数据代表 x 和 y 坐标?

谁能建议我哪里出错了? TIA

【问题讨论】:

  • 使用 numpy:import numpy as np; stepsPlot = np.array(stepsPlot); plt.plot(stepsPlot[:,0], stepsPlot[:,1], 'ro')

标签: python matplotlib


【解决方案1】:

你需要改变两件事:

  • 首先,像这样指定 x 和 y 轴:
  • 其次,你需要使用scatter而不是plot

所以,代码应该是:

import pylab as plt


stepsPlot = [[1, 0], [2, 0], [2, -1], [3, -1], [3, -2], [4, -2], [4, -1], [4, 0], [4, -1], [5, -1]]


plt.figure('Random Walk Scatter Plot')
plt.clf()
plt.title('Random Walk Scatter Plot')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
X = [item[0] for item in stepsPlot]
Y = [item[1] for item in stepsPlot]
plt.scatter(X, Y)
plt.show()

生成此图:

【讨论】:

  • 完美 :-) 非常感谢
  • 很高兴能帮上忙!!
【解决方案2】:

我认为这意味着 pylab 不理解数据 代表x和y坐标?

你的假设是正确的。你应该给绘图函数2个向量

1 包含所有 X 值 第二个包含所有 Y 值

【讨论】:

    【解决方案3】:

    @SysOverdrive 提到您需要提供两个向量。一种方法是将列表列表转换为数据框,然后将列作为两个向量提供。

    In [73]: df = pd.DataFrame(stepsPlot)
    
    In [74]: df
    Out[74]:
       0  1
    0  1  0
    1  2  0
    2  2 -1
    3  3 -1
    4  3 -2
    5  4 -2
    6  4 -1
    7  4  0
    8  4 -1
    9  5 -1
    
    In [75]: df.columns = ['X','Y']
    
    In [82]: import pylab as plt
        ...:
        ...: plt.figure('Random Walk Scatter Plot')
        ...: plt.clf()
        ...: plt.title('Random Walk Scatter Plot')
        ...: plt.xlabel('X Axis')
        ...: plt.ylabel('Y Axis')
        ...: plt.scatter(x=df['X'],y=df['Y'])
        ...: plt.show()
    

    【讨论】:

      猜你喜欢
      • 2013-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-02
      • 2015-01-09
      • 2019-11-27
      • 2018-06-02
      相关资源
      最近更新 更多