【问题标题】:Extra lines drawn by Axes.plot in matplotlib when passing odd number of lines传递奇数行时,matplotlib 中的 Axes.plot 绘制的额外线
【发布时间】:2021-10-27 12:49:38
【问题描述】:

我想绘制成对的点并用线将它们连接起来。这是一个包含两对点和两条线的最小示例:

points = [[0, 1], [1, 2], [1, 3], [2, 4]]
line_list  = [[[0, 1], [1, 2]], [[1, 3], [2, 4]]]

import matplotlib.pyplot as plt

fig = plt.figure()
ax = plt.axes()

scatter = ax.scatter(*list(zip(*points)))
lines = ax.plot(*line_list)

plt.show()

这符合我的预期:

接下来,我想添加另一对点,以及连接它们的额外线:

points = [[0, 1], [1, 2], [1, 3], [2, 4], [0, 2.5], [0.5, 3.5]]
line_list = [[[0, 1], [1, 2]], [[1, 3], [2, 4]], [[0, 2.5], [0.5, 3.5]]]

执行与上面相同的 matplotlib 代码,我得到了这个意外的结果,第三行终止于错误的点,还有一个额外的第四行:

我不知道为什么会这样。我最初的想法是,我将传递给 Axes.plot 的线阵列格式不正确,但令人困惑的是它在两行示例中有效。

【问题讨论】:

  • 仅供参考:彻底回答问题非常耗时。如果您的问题已解决,请通过接受最适合您的需求的解决方案表示感谢。 位于答案左上角的 / 箭头下方。如果出现更好的解决方案,则可以接受新的解决方案。如果您有 15 岁以上的声誉,您也可以使用 / 箭头对答案的有用性进行投票。 如果解决方案不能回答问题,请发表评论What should I do when someone answers my question?。谢谢

标签: python arrays list matplotlib plot


【解决方案1】:

老实说,我不明白为什么 ax.plot 会以这种方式行事。
特别是我很困惑ax.plot(0, 0) 开始画一条线,即使该点在您提供的任何列表中都不存在。

然而,你可以画出你想要的情节:

for line in line_list: ax.plot(*zip(*line))

完整代码

import matplotlib.pyplot as plt


points = [[0, 1], [1, 2], [1, 3], [2, 4], [0, 2.5], [0.5, 3.5]]
line_list = [[[0, 1], [1, 2]], [[1, 3], [2, 4]], [[0, 2.5], [0.5, 3.5]]]

fig = plt.figure()
ax = plt.axes()

ax.scatter(*zip(*points))
for line in line_list: ax.plot(*zip(*line))

plt.show()

(请注意,我在ax.scatter(*zip(*points)) 中简化了ax.scatter(*list(zip(*points)))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-14
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-07
    相关资源
    最近更新 更多