python - 在 python 中绘制,在键盘点击时更新

标签 python matplotlib plot

我一直在努力实现 Octave 中微不足道的事情:制作一系列情节,当我按下一个键时,情节就会发生变化。这是我的 Octave 代码示例。

x = [1:10];
for c=1:3
    plot(x,c.*x);
    hold off;
    input('a');
end

当我尝试在 python 中做同样的事情时,我意识到 python matplotlib 具有保存功能,这使它处于非阻塞模式,所以我必须使用鼠标关闭图形,以便下一个图形生产的。下一个数字位于屏幕上的其他随机位置。我怎样才能让python模仿上面的行为呢?我已经尝试了 ion()、ioff()、plt.show()、plt.draw() 的各种组合,但都没有成功。

最佳答案

如果你愿意,你可以做一些更有趣的事情,使用 mpl_connect

首先导入pylab

from pylab import *

然后定义一个可以连接到图形 Canvas 的 updateData 函数。

i = 1
def updateData(event):
    global i,x
    i +=1
    y = i*x
    data.set_data(x,y)
    ylim(y[0],y[-1])
    draw()

ix 在这种情况下是全局变量。 (这可以用更好的方式处理,这只是一个例子!)

然后,创建您的绘图并连接您定义的函数。

f = figure()
data, = plot(x,x)
i=1
f.canvas.mpl_connect("key_press_event",updateData)
show()

Whenever you hit any key in the keyboard (When the figure window is selected) the function updateData is called, i is incremented and the plot updated.

玩得开心!

关于python - 在 python 中绘制,在键盘点击时更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26538705/

相关文章:

python - Sklearn 中基于示例的 f 分数小于精度和召回率

python - Matplotlib 动画 fill_between 形状

python - 在 Anaconda 中运行 matplotlib 时出错

r - 什么是 %||% 运算符(在 ggplot2 中使用),它在哪里定义?

python - Python GAE datastoreAttributeError : 'NoneType' object has no attribute

python - python 中的函数会更改输入变量,这是为什么?

python - 在同一轴上绘制多个标签

r - 我如何绘制时间 (HH :MM:SS) in X axis in R

plot - Gnuplot:在图外添加键而不调整图大小

python - "Registration timeout"在非常基本的 Python IRC 机器人上