【问题标题】:Matplotlib python connect two scatter plots with lines for each pair of (x,y) values?Matplotlib python将两个散点图与每对(x,y)值的线连接起来?
【发布时间】:2019-02-12 22:22:07
【问题描述】:

我无法将散点图中的两组点相互连接起来,这样一条线(在此示例中,使用虚拟数据)将所有“前”点与相应的“后”点连接起来。 'marker = 'o-' 参数不适用于 plt。 scatter,但对于 plt.阴谋。关于如何连接相应值的建议?谢谢,希望这个问题有意义!

import matplotlib.pyplot as plt
import numpy as np
x1 = ["pre"] * 4
x2 = ["post"] * 4
y1 = [0.1, 0.15, 0.13, 0.25]
y2 = [0.85, 0.76, 0.8, 0.9]
plt.scatter(x1, y1, color='y')
plt.scatter(x2, y2, color='g')
plt.show()

【问题讨论】:

  • 也许你想多了。 for i in range(len(x1)): plt.plot([x1[i],x2[i]], [y1[i],y2[i]])
  • 是的,效果很好!我还添加了 marker = 'o' 以便出现端点。谢谢!

标签: python matplotlib scatter-plot


【解决方案1】:

虽然@ImportanceOfBeingErnest 已经为您提供了看似最简单的解决方案,但您可能有兴趣了解另一种解决方案来获得您想要的东西。你可以使用LineCollection

from matplotlib.collections import LineCollection

fig, ax = plt.subplots()

# Rest of your code

lines = [[x, list(zip([1]*4, y2))[i]] for i, x in enumerate(zip([0]*4, y1))]
print (lines)
# [[(0, 0.1), (1, 0.85)], [(0, 0.15), (1, 0.76)], [(0, 0.13), (1, 0.8)], [(0, 0.25), (1, 0.9)]]

lc = LineCollection(lines)
ax.add_collection(lc)
plt.show()

【讨论】:

  • 矫枉过正或重复?
  • 我在这里必须弄清楚如何在这里创建列表行。休息基于使用来自 SO 的 linecollection。我承认这是一种矫枉过正,这就是为什么我开始回答说你的建议是最简单的,但这只是一个替代方案。老实说,我其实很想看看如何使用行集合来解决这个问题;)
  • 嗯,所以如果这是一个问题,我会做verts = np.c_[np.zeros_like(y1),y1,np.ones_like(y2),y2].reshape(len(x1),2,2)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-13
  • 2011-10-03
相关资源
最近更新 更多