修改一行中的y数据 [英] Modify y data in a line
问题描述
我有以下脚本
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 = i>圆形(x)绘制,其中x是鼠标点击的横坐标.
Expected Behavior the original horizontal line y = 0 is cleared in response to a mouse click and a new horizontal line, y = round(x) is drawn, where x is the abscissa of the mouse click.
意外行为已清除原始水平线,并且未绘制新的水平线.
Unexpected Behavior the original horizontal line is cleared and no new horizontal line is drawn.
我使用
line.get_ydata()
检查了交互式 IPython 终端,回调确实更新了纵坐标.I checked in an interactive IPython terminal, using
line.get_ydata()
, that the callback does update the ordinates.我不得不说我玩过
plt.ion()
,在回调中重复plt.show()
,使用a1.draw()
等总是无济于事.I have to say that I've played with
plt.ion()
, repeatingplt.show()
in the callback, usinga1.draw()
, etc always to no avail.我知道我可能遗漏了显而易见的东西,但我在这里......
I understand that I'm probably missing the obvious, but here I am...
推荐答案
您的代码运行良好,只是在可见 y 限制之外绘制了线条.
Your code is working fine, it's just drawing the line outside of the visible y-limits.
- 或者您事先强制执行适当的 y 限制(例如,在
plt.show()
之前使用ax.set_ylim(-1,5)
) - 或在调用
fig.canvas.draw_idle()
之前的mod_ydata()
中添加以下几行:
- either you enforce proper y-limits beforehand (e.g. using
ax.set_ylim(-1,5)
beforeplt.show()
) - or you add the following lines inside
mod_ydata()
, right before the call tofig.canvas.draw_idle()
:
ax.relim() ax.autoscale_view()
尽管后者使线条的运动"有点难以看到.
although the latter makes the "movement" of the line kind of hard to see.
这篇关于修改一行中的y数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- 或者您事先强制执行适当的 y 限制(例如,在