How to update matplotlib's imshow() window interactively?


To plot interactive matplotlib’s imshow window, we can take the following steps −

  • Using the subplots() method, create a figure and a set of subplots.

  • Create an array to plot an image, using numpy.

  • Display the image using the imshow() method.

  • To make a slider axis, create an axes and a slider, with facecolor=yellow.

  • To update the image, while changing the slider, we can write a user-defined method, i.e., update(). Using the draw_idle() method, request a widget redraw once the control returns to the GUI event loop.

  • To display the figure, use the show() method.

Example

import numpy as np
from matplotlib import pyplot as plt
from matplotlib.widgets import Slider
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
fig, ax = plt.subplots()
image = np.random.rand(3, 3)
img = ax.imshow(image)
axcolor = 'yellow'
ax_slider = plt.axes([0.20, 0.01, 0.65, 0.03], facecolor=axcolor)
slider = Slider(ax_slider, 'Slide->', 0.1, 30.0, valinit=2)
def update(val):
   ax.imshow(np.random.rand(3, 3))
   fig.canvas.draw_idle()
slider.on_changed(update)
plt.show()

Output

Updated on: 10-Apr-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements