python - 通过 matplotlib 图向后和向前滚动

标签 python matplotlib

我的代码使用 matplotib 从数据中生成了一些图表,我希望能够在现场演示中向前和向后滚动它们(可能通过按向前和向后键或使用鼠标)。目前我必须将每个单独保存为图像,然后使用单独的图像查看器滚动浏览它们。有没有办法完全从 python 中做到这一点?

最佳答案

一个简单的实现方法是在列表中存储 x 和 y 数组的元组,然后使用处理程序事件选择要绘制的下一个 (x,y) 对:

import numpy as np
import matplotlib.pyplot as plt

# define your x and y arrays to be plotted
t = np.linspace(start=0, stop=2*np.pi, num=100)
y1 = np.cos(t)
y2 = np.sin(t)
y3 = np.tan(t)
plots = [(t,y1), (t,y2), (t,y3)]

# now the real code :) 
curr_pos = 0

def key_event(e):
    global curr_pos

    if e.key == "right":
        curr_pos = curr_pos + 1
    elif e.key == "left":
        curr_pos = curr_pos - 1
    else:
        return
    curr_pos = curr_pos % len(plots)

    ax.cla()
    ax.plot(plots[curr_pos][0], plots[curr_pos][1])
    fig.canvas.draw()

fig = plt.figure()
fig.canvas.mpl_connect('key_press_event', key_event)
ax = fig.add_subplot(111)
ax.plot(t,y1)
plt.show()

在此代码中,我选择了 rightleft 箭头进行迭代,但您可以更改它们。

关于python - 通过 matplotlib 图向后和向前滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18390461/

相关文章:

python - 带颜色条的 Matplotlib 3D 散点图

python - Quiver 图箭头纵横比

python - 尝试在 python 中上传到 MySQL 数据库时出现完整性错误

python - gTTS Python 脚本在后台获取 tcgetattr() : Inappropriate ioctl for device

python - 使用 Elsevier Scopus API 获取论文引用

python - 给3分和一个情节圈

python - 查找 numpy.where 返回的值的数量

python - 类成员定期更新的线程

用于屏幕坐标和频率字典的 Python 热图

python - 使用 matplotlib 的时间序列中的自定义日期范围(x 轴)