简体   繁体   English

Matplotlib:imshow中的set_data没有效果

[英]Matplotlib: no effect of set_data in imshow for the plot

I have a strange error which I can't fix without your help. 我有一个奇怪的错误,如果没有你的帮助,我无法修复。 After I set an image with imshow in matplotlib it stays the same all the time even if I change it with the method set_data . 在matplotlib中使用imshow设置图像后,即使我用方法set_data更改它,它也始终保持不变。 Just take a look on this example: 看看这个例子:

import numpy as np
from matplotlib import pyplot as plt


def newevent(event):
    haha[1,1] += 1
    img.set_data(haha)
    print img.get_array()    # the data is change at this point
    plt.draw()

haha = np.zeros((2,2))
img = plt.imshow(haha)
print img.get_array()        # [[0,0],[0,0]]
plt.connect('button_press_event', newevent)
plt.show()

After I plot it, the method set_data doesn't change anything inside the plot. 绘制之后,方法set_data不会更改绘图内的任何内容。 Can someone explain me why? 有人能解释一下为什么吗?

EDIT 编辑

Just added a few lines to point out what I actually want to do. 只是添加了几行来指出我真正想做的事情。 I want to redraw the data after I press a mouse button. 我想在按下鼠标按钮后重绘数据。 I don't want to delete the whole figure, because it would be stupid if only one thing changes. 我不想删除整个数字,因为如果只有一件事发生变化就会很愚蠢。

The problem is because you have not updated the pixel scaling after the first call. 问题是因为您在第一次调用后没有更新像素缩放。

When you instantiate imshow , it sets vmin and vmax from the initial data, and never touches it again. 当您实例化imshow ,它会从初始数据中设置vminvmax ,而不会再次触摸它。 In your code, it sets both vmin and vmax to 0, since your data, haha = zeros((2,2)) , is zero everywhere. 在您的代码中,它将vminvmax都设置为0,因为您的数据haha = zeros((2,2))在任何地方都为零。

Your new event should include autoscaling with img.autoscale() , or explicitly set new scaling terms by setting img.norm.vmin/vmax to something you prefer. 您的新事件应包括使用img.autoscale()自动缩放,或通过将img.norm.vmin/vmax设置为您喜欢的内容来显式设置新的缩放术语。

The function to set the new vmin and vmax is: 设置新vminvmax是:

img.set_clim(vmin=new_vim, vmax=new_vmax)

Does this give you the output you expect? 这会给你预期的输出吗?

import numpy as np
from matplotlib import pyplot as plt

haha = np.zeros((2,2))
img = plt.imshow(haha)
print img.get_array()        # [[0,0],[0,0]]
haha[1,1] += 1

img.set_data(haha)    
img = plt.imshow(haha)       # <<------- added this line  
print img.get_array()        # [[0,0],[0,1]]
plt.show()

When I display the plot twice (once before the change to haha , and at the end), it does change. 当我显示两次图表时(在更改haha之前和结尾之前),它确实会发生变化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM