我想在补充绘图中绘制数据,它对应于主绘图中鼠标悬停的当前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中设置或释放断点。在
如何规范正确的行为?在
更改第二个图形后,您忘记刷新它。在末尾添加
fig2.canvas.draw_idle()
。在请注意,这将在每个鼠标移动事件上创建新的圆圈和艺术家,这是相当低效的。您希望创建这些艺术家一次,只更新他们的属性。在
下面的程序运行得更顺利。在
^{pr2}$相关问题 更多 >
编程相关推荐