我想使用Matplotlib逐片绘制3D体积。 鼠标滚动以更改索引。我的计划如下:
#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]
。
但是,如果将图像set_array方法更改为ax.show()
。图开始再次渲染。但是与ax.images[0].set_array()
方法相比,轴imshow功能真的很慢。
如何解决此问题?真的想用set_array()
方法。非常感谢你。
附加了一个简单的可执行脚本。 plot.py@googledrive
答案 0 :(得分:2)
您需要始终处理相同的图像。最好给这个名字
img = ax.imshow(volume[ax.index])
然后,您可以使用set_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()