如何创建matplotlib幻灯片?

时间:2016-07-22 17:47:00

标签: python matplotlib cross-platform slideshow

下面的Python / pyplot代码生成四个数字和四个窗口。我需要打开一个窗口显示fig1的代码。然后,当用户按下右箭头键或右箭头键时,同一窗口清除fig1并显示图2。因此,用户基本上只选择四个图中的一个用于在幻灯片放映中观看。我在文档和在线搜索了一个答案,没有成功。我编辑了这个问题,以显示四个图中出现的六个轴的定义。看来必须将轴与一个图形相关联,然后绘制,清除和重绘轴以模拟默认GUI中的幻灯片显示?

import numpy as np
import matplotlib.pyplot as plt

fig1 = plt.figure()
ax1 = fig1.add_subplot(3, 1, 1)
ax2 = fig1.add_subplot(3, 1, 2, sharex=ax1)
ax3 = fig1.add_subplot(3, 1, 3, sharex=ax1)
fig2 = plt.figure()
ax4 = fig2.add_subplot(1, 1, 1)
fig3 = plt.figure()
ax5 = fig2.add_subplot(1, 1, 1)
fig4 = plt.figure()
ax6 = fig2.add_subplot(1, 1, 1)
plt.show()

理想情况下,我想设置后端以确保在MacOS,Linux和Windows上具有相同的代码功能。但是,如果有必要的话,我会很满意在Windows 7上使用非常基本的幻灯片,并在以后开发其他操作系统。

1 个答案:

答案 0 :(得分:3)

也许是这样的: (点击图表切换)

import matplotlib.pyplot as plt
import numpy as np

i = 0

def fig1(fig):
    ax = fig.add_subplot(111)
    ax.plot(x, np.sin(x))


def fig2(fig):
    ax = fig.add_subplot(111)
    ax.plot(x, np.cos(x))


def fig3(fig):
    ax = fig.add_subplot(111)
    ax.plot(x, np.tan(x))


def fig4(fig):
    ax1 = fig.add_subplot(311)
    ax1.plot(x, np.sin(x))
    ax2 = fig.add_subplot(312)
    ax2.plot(x, np.cos(x))
    ax3 = fig.add_subplot(313)
    ax3.plot(x, np.tan(x))

switch_figs = {
    0: fig1,
    1: fig2,
    2: fig3,
    3: fig4
}

def onclick1(fig):
    global i
    print(i)
    fig.clear()
    i += 1
    i %= 4
    switch_figs[i](fig)
    plt.draw()

x = np.linspace(0, 2*np.pi, 1000)
fig = plt.figure()
switch_figs[0](fig)
fig.canvas.mpl_connect('button_press_event', lambda event: onclick1(fig))

plt.show()