【问题标题】:How to plot two lists of tuples with Matplotlib如何使用 Matplotlib 绘制两个元组列表
【发布时间】:2021-11-22 17:55:45
【问题描述】:

我有两个列表,其中每个元素都是一个元组,应该被解释为

x = [(x1_begin, x1_end), (x2_begin, x2_end), ... , (xn_begin, xn_end)]
y = [(y1_begin, y1_end), (y2_begin, y2_end), ... , (yn_begin, yn_end)] 

在一张图中,我想为所有 i 绘制所有这些点并(yi_begin, yi_end)(xi_begin, xi_end) 之间画线。

以下代码设法绘制所有点。但我不确定如何在点之间正确绘制线条。非常感谢任何帮助。

import matplotlib.pyplot as plt

x = [(1, 27), (32, 55), (56, 80), (84, 103)]
y = [(5, 7), (3, 6), (4, 9), (6, 11)]

fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(x, y, color='black')
plt.show()

【问题讨论】:

  • 我有点困惑。你的 x 和 y 对应 x, y 轴上的坐标吗?
  • @Spinor8 是的,所以 x 轴的范围应该是 1 到 103,y 轴的范围应该是 3 到 11。希望能澄清你的问题?
  • 所以你的数据本质上是:list_1 = [(line1_start_x, line1_end_x) ,.... ] 和 list_2 = [(line1_start_y, line1_end_y) ....],对吧?
  • (yi_begin, yi_end) vs (xi_begin, xi_end) 表示 (xi_begin,yi_begin) 到 (xi_end,yi_end) 之间的一条线?
  • 另外,似乎是 this question 的副本。请在发帖前使用搜索。

标签: python matplotlib


【解决方案1】:

遍历你的元组:

import matplotlib.pyplot as plt

x = [(1, 27), (32, 55), (56, 80), (84, 103)]
y = [(5, 7), (3, 6), (4, 9), (6, 11)]

fig = plt.figure()
ax = fig.add_subplot(111)
for xt, yt in zip(x,y):
    ax.plot(xt, yt, color='black')
plt.show()

【讨论】:

    【解决方案2】:

    如果您确实要求每个元组一行,这里是代码。

    fig = plt.figure()
    ax = fig.add_subplot(111)
    assert len(x) == len(y)
    for i in range(len(x)):
        plt.plot(x[i], y[i])
    plt.show()
    

    给你

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-22
      • 1970-01-01
      • 2021-03-28
      • 2019-05-10
      • 1970-01-01
      • 2021-10-13
      • 2018-02-24
      相关资源
      最近更新 更多