下面的 Python/pyplot 代码生成了四个图形和四个窗口。我需要打开一个显示图 1 的窗口的代码。然后,当用户按下右箭头按钮或右箭头键时,同一窗口会清除图 1 并显示图 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 上获得一个非常基本的幻灯片,并在必要时为其他操作系统开发。
最佳答案
也许是这样的: (点击图表切换)
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()
关于python - 如何创建 matplotlib 幻灯片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38532522/