如何在鼠标移动到另一个绘图时更新一个绘图?

2024-10-01 00:24:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在补充绘图中绘制数据,它对应于主绘图中鼠标悬停的当前X值。在

我编码了

import math

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(dpi=100, figsize=(5, 5))
x = np.arange(0, 6, 0.1)
plt.plot(x, np.sin(x), 'r')

fig2, ax2 = plt.subplots(dpi=100, figsize=(5, 5))


def plot_ray(angle, y):
    circle = plt.Circle((0, 0), 1, color='b', fill=False)
    length = y / math.sin(angle)
    line = plt.Line2D([0, length * math.cos(angle)], [0, length * math.sin(angle)])
    ax2.clear()
    ax2.set_xlim(-2, 2)
    ax2.set_ylim(-2, 2)
    ax2.add_artist(circle)
    ax2.add_artist(line)


def mouse_move(event):
    x = event.xdata
    y = event.ydata
    if x is not None and y is not None:
        angle = x
        plot_ray(angle, y)


cid = fig.canvas.mpl_connect('motion_notify_event', mouse_move)

plt.show(block=True)

不幸的是,ax2的行为是不可预测的。它不是在我鼠标悬停时更新的,直到我单击fig2窗口。或者它不会更新,直到我在pycharm中设置或释放断点。在

enter image description here

如何规范正确的行为?在


Tags: importevent绘图plotasnpfigplt
1条回答
网友
1楼 · 发布于 2024-10-01 00:24:40

更改第二个图形后,您忘记刷新它。在末尾添加fig2.canvas.draw_idle()。在

def mouse_move(event):
    x = event.xdata
    y = event.ydata
    if x is not None and y is not None:
        angle = x
        plot_ray(angle, y)
        fig2.canvas.draw_idle()

请注意,这将在每个鼠标移动事件上创建新的圆圈和艺术家,这是相当低效的。您希望创建这些艺术家一次,只更新他们的属性。在

下面的程序运行得更顺利。在

^{pr2}$

相关问题 更多 >