[英]How do I use mpl_connect to highlight points different from the one selected?
I have a simple time series (x, y, t)
.我有一个简单的时间序列
(x, y, t)
。 I have plotted all the points (x,y)
on a two-dimensional scatter plot using matplotlib and am able to access the time value for each point by making "t"
a label and using mplcursors
connect
:我已经使用 matplotlib 在二维散点图 plot 上绘制了所有点
(x,y)
,并且能够通过将"t"
设为 label 并使用mplcursors
connect
来访问每个点的时间值:
labels = data.index
points = plt.scatter(data['Column1'], data['Column2'], color=color)
cursor = mplcursors.cursor(points, hover=2)
cursor.connect("add", lambda sel: sel.annotation.set_text(labels[sel.index]))
I am looking for a way that upon selection of a point, that point as well as the next point in the time series will be highlighted, so the viewer can see where the series is going.我正在寻找一种方法,在选择一个点后,该点以及时间序列中的下一个点将突出显示,以便观众可以看到该系列的发展方向。 I can always put the coordinates of the following point in as a label, but I would like the visual.
我总是可以将以下点的坐标输入为 label,但我想要视觉效果。
You can draw a small circle, eg via plt.scatter
at the position of the next point.您可以在下一个点的 position 处绘制一个小圆圈,例如通过
plt.scatter
。 Appending it to sel.extras
takes care of removing it as soon as the current highlight is removed.将它附加到
sel.extras
会在当前突出显示被删除后立即将其删除。
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import mplcursors
def annotation_func(sel):
if sel.index < len(data) - 1:
x0, y0 = data.iloc[sel.index][['Column1', 'Column2']]
x1, y1 = data.iloc[sel.index + 1][['Column1', 'Column2']]
circle = plt.scatter(x1, y1, s=100, fc='none', ec='red', lw=2)
line, = plt.plot([x0, x1], [y0, y1], c='red', lw=1, ls=':')
sel.extras.append(circle)
sel.extras.append(line)
sel.annotation.set_text(data.index[sel.index])
data = pd.DataFrame({'Column1': np.arange(30),
'Column2': np.random.randn(30).cumsum()},
index=[f'P{i}' for i in range(30)])
points = plt.scatter(data['Column1'], data['Column2'], color='turquoise')
cursor = mplcursors.cursor(points, hover=2)
cursor.connect("add", annotation_func)
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.