fig, ax = plt.subplots() ax.plot(new_name_lst, x_list, label='velocity_x') ax.plot(new_name_lst, y_list, label='velocity_y') ax.plot(new_name_lst, list3, label='velocity') # leg = ax.legend(loc='upper left', fancybox=True, shadow=True) leg.get_frame().set_alpha(0.5) lines = [l for l in ax.lines] lined = dict() for legline, origline in zip(leg.get_lines(), lines): legline.set_picker(True) lined[legline] = origline def onpick(event): legline = event.artist origline = lined[legline] visible = not origline.get_visible() origline.set_visible(visible) if visible: legline.set_alpha(1.0) else: legline.set_alpha(0.2) fig.canvas.draw() fig.canvas.mpl_connect('pick_event', onpick) plt.show()这个代码加一个跟随鼠标的虚线
时间: 2023-12-09 17:05:55 浏览: 138
你可以尝试添加以下代码来实现跟随鼠标的虚线:
```python
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
# 假设你已经有了名为 new_name_lst、x_list、y_list 和 list3 的变量
ax.plot(new_name_lst, x_list, label='velocity_x')
ax.plot(new_name_lst, y_list, label='velocity_y')
ax.plot(new_name_lst, list3, label='velocity')
leg = ax.legend(loc='upper left', fancybox=True, shadow=True)
leg.get_frame().set_alpha(0.5)
lines = [l for l in ax.lines]
lined = dict()
for legline, origline in zip(leg.get_lines(), lines):
legline.set_picker(True)
lined[legline] = origline
def onpick(event):
legline = event.artist
origline = lined[legline]
visible = not origline.get_visible()
origline.set_visible(visible)
if visible:
legline.set_alpha(1.0)
else:
legline.set_alpha(0.2)
fig.canvas.draw()
# 添加跟随鼠标的虚线
if isinstance(event.artist, plt.Line2D):
xdata = event.artist.get_xdata()
ydata = event.artist.get_ydata()
x = event.mouseevent.xdata
y = event.mouseevent.ydata
idx = np.searchsorted(xdata, x)
if idx < len(xdata) and abs(x - xdata[idx]) > abs(x - xdata[idx-1]):
idx -= 1
if idx >= len(xdata) or idx == 0:
return
x = xdata[idx]
y = ydata[idx]
if not hasattr(ax, 'vline'):
ax.vline = ax.axvline(x=x, color='k', linestyle='--')
else:
ax.vline.set_xdata([x, x])
ax.vline.set_ydata([min(y, ax.get_ylim()[1]), max(y, ax.get_ylim()[0])])
fig.canvas.mpl_connect('pick_event', onpick)
plt.show()
```
这个代码会在图形中添加一个跟随鼠标的垂直虚线,当鼠标拾取到某个线条时,虚线会跟随鼠标移动到该线条上。
阅读全文