Python 如何刷新Matplotlib图形的轴图像
我想使用Matplotlib逐片绘制三维体积。 鼠标滚动以更改索引。我的程序如下:Python 如何刷新Matplotlib图形的轴图像,python,matplotlib,figure,imshow,Python,Matplotlib,Figure,Imshow,我想使用Matplotlib逐片绘制三维体积。 鼠标滚动以更改索引。我的程序如下: #Mouse scroll event. def mouse_scroll(event): fig = event.canvas.figure ax = fig.axes[0] if event.button == 'down': next_slice(ax) fig.canvas.draw() #Next slice func. def previous_slice(ax): volu
#Mouse scroll event.
def mouse_scroll(event):
fig = event.canvas.figure
ax = fig.axes[0]
if event.button == 'down':
next_slice(ax)
fig.canvas.draw()
#Next slice func.
def previous_slice(ax):
volume = ax.volume
ax.index = (ax.index - 1) % volume.shape[0]
#ax.imshow(volume[ax.index])
ax.images[0].set_array(volume[ax.index])
图在主函数中初始化。比如:
fig, ax = plt.subplots()
ax.volume = volume # volume is a 3D data, a 3d np array.
ax.index = 1
ax.imshow(volume[ax.index])
fig.canvas.mpl_connect('scroll_event', mouse_scroll)
即使我不明白ax.images是什么,但一切都很顺利。但是,当我用新的卷数据替换ax.volume
时出现了问题。它突然停下来渲染!调试到代码中,在每次事件回调时正确设置了ax.image[0]
但是,如果将图像集数组方法更改为ax.show()
。图再次开始渲染。但是与ax.images[0].set_array()
方法相比,axes imshow函数的速度非常慢
我如何解决这个问题?确实要使用set\u array()
方法。多谢各位
附加了一个简单的可执行脚本。
您需要始终处理同一个图像。最好给这个起个名字
img = ax.imshow(volume[ax.index])
然后可以使用set\u data
为其设置数据
import numpy as np
import matplotlib.pyplot as plt
#Mouse scroll event.
def mouse_scroll(event):
fig = event.canvas.figure
ax = fig.axes[0]
if event.button == 'down':
next_slice(ax)
fig.canvas.draw()
#Next slice func.
def next_slice(ax):
volume = ax.volume
ax.index = (ax.index - 1) % volume.shape[0]
img.set_array(volume[ax.index])
def mouse_click(event):
fig = event.canvas.figure
ax = fig.axes[0]
volume = np.random.rand(10, 10, 10)
ax.volume = volume
ax.index = (ax.index - 1) % volume.shape[0]
img.set_array(volume[ax.index])
fig.canvas.draw_idle()
if __name__ == '__main__':
fig, ax = plt.subplots()
volume = np.random.rand(40, 40, 40)
ax.volume = volume # volume is a 3D data, a 3d np array.
ax.index = 1
img = ax.imshow(volume[ax.index])
fig.canvas.mpl_connect('scroll_event', mouse_scroll)
fig.canvas.mpl_connect('button_press_event', mouse_click)
plt.show()
提供这样一种方法总是有意义的,即人们可以复制不想要的行为,以帮助找到解决方案。虽然为现有对象创建自定义属性通常不是一个好主意,但我不确定这是否会在这种情况下导致任何问题。显然,代码看起来不错。但是没有一个是不能测试的。@ImportanceOfBeingErnest非常感谢您的建议。我附加了一个简单的可执行代码。