python - 如何刷新Matplotlib图形的轴图像

标签 python matplotlib figure imshow

我想使用 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() 方法相比,axes imshow 函数确实很慢。

如何解决这个问题?真的想使用 set_array() 方法。非常感谢。

附上一个简单的可执行脚本。 plot.py@googledrive

最佳答案

您需要始终处理同一个图像。最好给它起个名字

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()

关于python - 如何刷新Matplotlib图形的轴图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47572067/

相关文章:

python - django返回每个用户的最新记录

python - 为什么我的时间数据与格式不匹配 "' %a %b %d %M : %H: %S %Y'"

python - 当 matplotlib 中的数字有上标时,如何对齐刻度标签?

python - 在matplotlib中将多个图形保存到一个pdf文件

javascript - 在 SVG 元素中使用带有 <figure> 的自定义 onHover

html - <figure> 元素可以只包含 <figcaption> 而没有图像吗?

python - 在没有 conda 的情况下安装 gdcm

python - 在Caffe中训练GoogLeNet时如何向输入图像添加外部特征?

plot - 在子图之间共享等值线图属性

matlab - 扩展matlab中的subplot函数