繁体   English   中英

如何使用 matplotlib 在两条单独的 plot 行上的标记之间创建新行 plot?

[英]How to plot a new line between the markers on two separate plot lines using matplotlib?

我创建了一个图表,当前显示每个索引的两个图(仅标记)。 我想创建第三个 plot (带线)连接前两个条目。

plot 目前的外观如何:

在此处输入图像描述

我怎样才能 plot 一条线将每个项目的红点连接到蓝点?

我当前绘制 plot 的代码如下所示:

plt.figure(figsize=(8,7))
plt.plot(points_vs_xpoints["xpts"],points_vs_xpoints.index, label="Projected", linestyle = 'None', marker="o")
plt.plot(points_vs_xpoints["pts"], points_vs_xpoints.index, label="Actual", linestyle = 'None', marker="o", markeredgecolor="r", markerfacecolor='None')

plt.xticks(np.arange(0, 100, 10))
plt.xticks(rotation=90)
plt.legend()
plt.grid(color='grey', linewidth=0.2)
plt.tight_layout()
plt.show()

如果我正确理解了您的要求,这应该可以解决问题。

from matplotlib import pyplot as plt
from matplotlib.collections import LineCollection

plt.figure(figsize=(8,7))
f, ax = plt.subplots(1, 1)
ax.plot(points_vs_xpoints["xpts"],points_vs_xpoints.index, label="Projected", linestyle = 'None', marker="o")
ax.plot(points_vs_xpoints["pts"], points_vs_xpoints.index, label="Actual", linestyle = 'None', marker="o", markeredgecolor="r", markerfacecolor='None')

lines = LineCollection([[[el[0], points_vs_xpoints.index[i]], [el[1], points_vs_xpoints.index[i]]] for i, el in enumerate(zip(points_vs_xpoints["xpts"],points_vs_xpoints["pts"]))], label='Connection', linestyle='dotted')
ax.add_collection(lines)

ax.set_xticks(np.arange(0, 100, 10))
plt.tick_params(rotation=90)
ax.legend()
ax.grid(color='grey', linewidth=0.2)
f.tight_layout()
plt.show()

在此处查看结果图

编辑

我错误地认为你的索引是一个数字。 使用字符串索引,您可以尝试这样的事情

from matplotlib import pyplot as plt
from matplotlib.collections import LineCollection

plt.figure(figsize=(8,7))
f, ax = plt.subplots(1, 1)
ax.plot(points_vs_xpoints["xpts"],points_vs_xpoints.index, label="Projected", linestyle = 'None', marker="o")
ax.plot(points_vs_xpoints["pts"], points_vs_xpoints.index, label="Actual", linestyle = 'None', marker="o", markeredgecolor="r", markerfacecolor='None')

# Let's go with a simple index
lines = LineCollection([[[el[0], i], [el[1], i]] for i, el in enumerate(zip(points_vs_xpoints["xpts"],points_vs_xpoints["pts"]))], label='Connection', linestyle='dotted')
ax.add_collection(lines)

# Change for labels rotation
ax.set_xticklabels(np.arange(0, 100, 10), rotation=90)
ax.legend()
ax.grid(color='grey', linewidth=0.2)
f.tight_layout()
plt.show()

在此处查看结果图

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM