【问题标题】:Strange output in matplotlibmatplotlib 中的奇怪输出
【发布时间】:2021-06-19 08:22:53
【问题描述】:

谁能解释为什么我在运行这段代码时得到这个奇怪的输出:

import matplotlib.pyplot as plt
import numpy as np
def x_y():
    return np.random.randint(9999, size=1000), np.random.randint(9999, size=1000)
plt.plot(x_y())
plt.show()

输出:

【问题讨论】:

    标签: python matplotlib graph


    【解决方案1】:

    您的数据是两个 1000 长度数组的元组。

    def x_y():
        return np.random.randint(9999, size=1000), np.random.randint(9999, size=1000)
    xy = x_y()
    print(len(xy))
    # > 2
    print(xy[0].shape)
    # > (1000,)
    

    让我们阅读pyplot's documentation

    plot(y) # 使用 x 作为索引数组 0..N-1 绘制 y

    因此 pyplot 将在 (0, xy[0][i])(1, xy[1][i]) 之间绘制一条线,for i in range(1000)

    您可能会尝试这样做:

    plt.plot(*x_y())
    

    这一次,它将绘制由线连接的 1000 个点:(xy[0][i], xy[1][i]) for i in range 1000

    然而,这些线条在这里并不代表任何东西。因此,您可能希望查看各个点:

    plt.scatter(*x_y())
    

    【讨论】:

      【解决方案2】:

      您的函数 x_y 返回一个元组,将每个元素分配给一个变量会给出正确的输出。

      import matplotlib.pyplot as plt
      import numpy as np
      def x_y():
          return np.random.randint(9999, size=1000), np.random.randint(9999, size=1000)
      x, y = x_y()
      plt.plot(x, y)
      plt.show()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-03
        • 2015-02-18
        • 2011-06-14
        • 2013-06-04
        • 2021-02-08
        • 2014-12-27
        相关资源
        最近更新 更多