我有以下脚本
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
fig, ax = plt.subplots()
# draw a horizontal line y=0
line, = ax.plot(x, [0 for _ in x])
def mod_ydata(ev):
X = ev.xdata
if X is not None:
n = round(X)
line.set_ydata([n for _ in x])
fig.canvas.draw_idle()
fig.canvas.mpl_connect('button_press_event', mod_ydata)
plt.show()
预期的行为会清除原始水平线 y = 0 ,以响应鼠标单击和新的水平线 y = 回合(x) 绘制,其中 x 是鼠标单击的横坐标。
意外行为已清除原始水平线,并且未绘制新的水平线。
我使用line.get_ydata()
在交互式IPython终端中检查了回调确实更新了纵坐标。
我不得不说我曾经玩过plt.ion()
,在回调中重复使用plt.show()
,在重复中反复使用a1.draw()
,等等都无济于事。
我知道我可能缺少明显的东西,但是我在这里...
答案 0 :(得分:0)
您的代码运行正常,只是在可见的y限制之外画线。
ax.set_ylim(-1,5)
之前使用plt.show()
)mod_ydata()
调用之前的fig.canvas.draw_idle()
内添加以下几行:ax.relim()
ax.autoscale_view()
尽管后者使该行的“运动”很难看清。