简体   繁体   中英

How do I update the extent of imshow in matplotlib?

When updating an "imshow" plot in matplotlib, it's best to use im.set_data, rather than using ax.imshow repeatedly in the loop. But what if the extent of the data is changing? Is it possible to update the extent of the data on each iteration of the loop?

Here is an example:

import numpy as np 
import matplotlib.pyplot as plt
import time

ax = plt.subplot(111)
plt.ion()
plt.show()

count = 0
for size in np.linspace(1,3,10):
    x = np.linspace(-size,size,100)
    y = np.linspace(-size,size,100)

    X,Y = np.meshgrid(x,y)
    R   = (X**2+Y**2)**0.5

    Z = np.sin(R)/R
    ext =(-size,size,-size,size)

    if count == 0:
        im = plt.imshow(Z,extent=ext)
    else:
        im.set_data(Z)
        # Update the extent of the data

    plt.draw()
    plt.pause(0.5)
    ax.set_xlim(-size,size)
    ax.set_ylim(-size,size)

    count += 1

plt.ioff()
plt.show()

在此处输入图片说明

The colored region should take up the entire axes if I could update the extent properly.

In your example, im.set_extent(ext) .

More generally, though, almost any kwarg you can pass in to a matplotlib artist during initialization will have get_foo and set_foo methods. (That's actually how initialization works and how artist.set(...) and plt.setp works, as well.)

If you're looking for how to change a given property, the first place to look is a set_<name> method.

There are exceptions to this. For example, scatter returns a Collection , so you need to call set_offsets instead of set_xy to change the x, y data. Generally speaking, though, it's consistent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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