matplotlib.pyplot.imshow() in Python
Last Updated :
05 Apr, 2025
matplotlib.pyplot.imshow() function in Python is used to display images in a plot. It is part of the matplotlib library and allows you to visualize images as 2D data. This function is widely used for displaying images, matrices, or heatmaps where each value in the array corresponds to a color. Example:
Python
import numpy as np
import matplotlib.pyplot as plt
a = np.random.random((10, 10))
# Display the array as an image
plt.imshow(a, cmap='viridis', interpolation='nearest')
plt.colorbar()
plt.show()
Output
array as an imageExplanation:
- np.random.random((10, 10)) creates a 10x10 array of random numbers between 0 and 1.
- imshow() visualizes the array as an image, using the 'viridis' colormap and 'nearest' interpolation.
- plt.colorbar() adds a colorbar to the side of the image, showing the value-to-color mapping.
Syntax
matplotlib.pyplot.imshow(X, cmap=None, norm=None, *, aspect=None, interpolation=None, alpha=None, vmin=None, vmax=None, colorizer=None, origin=None, extent=None, interpolation_stage=None, filternorm=True, filterrad=4.0, resample=None, url=None, data=None, **kwargs)
Parameters:
- X: The input data (2D array or image) to be displayed. This is typically a numpy array or an image.
- cmap: The colormap to be used for displaying the data. This maps the data values to colors. If not provided, a default colormap is used.
- norm: A normalization object that scales the data values before mapping them to colors (e.g., Normalize, LogNorm, etc.). It controls how data values are transformed into colors.
- vmin, vmax: These parameters control the color scaling. Values in the image below vmin are mapped to the lowest color, and values above vmax are mapped to the highest color.
- alpha: Sets the transparency level of the image, where 0 is fully transparent and 1 is fully opaque.
- aspect: This parameter is used to controls the aspect ratio of the axes.
- interpolation: This parameter is the interpolation method which used to display an image.
- origin: This parameter is used to place the [0, 0] index of the array in the upper left or lower left corner of the axes.
- resample: This parameter is the method which is used for resembling.
- extent: This parameter is the bounding box in data coordinates.
- filternorm: This parameter is used for the antigrain image resize filter.
- filterrad: This parameter is the filter radius for filters that have a radius parameter.
- url: This parameter sets the url of the created AxesImage.
- data: Data source for the image. This is an optional parameter that can be used to specify an object from which the image data should be fetched
- **kwargs: Other keyword arguments for further customization (e.g., setting axis labels, figure size, etc.).
Reurn Value: imshow() function returns an AxesImage object, which is an instance of the matplotlib.image.AxesImage class. This object represents the image displayed on the axes and can be used to further customize or interact with the image after it has been plotted.
Examples of matplotlib.pyplot.imshow()
1. Displaying 2D Data with imshow() and Custom Color Range
This code demonstrates how to display a 2D data array using imshow() with a custom color range. It sets specific vmin and vmax values to control the color intensity.
Python
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LogNorm
dx, dy = 0.015, 0.05
y, x = np.mgrid[slice(-4, 4 + dy, dy),
slice(-4, 4 + dx, dx)]
z = (1 - x / 3. + x ** 5 + y ** 5) * np.exp(-x ** 2 - y ** 2)
z = z[:-1, :-1]
z_min, z_max = -np.abs(z).max(), np.abs(z).max()
c = plt.imshow(z, cmap ='Greens', vmin = z_min, vmax = z_max,
extent =[x.min(), x.max(), y.min(), y.max()],
interpolation ='nearest', origin ='lower')
plt.colorbar(c)
plt.title('matplotlib.pyplot.imshow() function Example', fontweight ="bold")
plt.show()
Output

Explanation: We first create a 2D grid of values using numpy.mgrid and compute a function over the grid. Then, we use imshow() to display this 2D array. The vmin and vmax parameters are set to the minimum and maximum of the data, ensuring the color map is scaled accordingly. The colormap 'Greens' is used, and the extent parameter specifies the limits of the x and y axes. We also use origin='lower' to set the origin of the image at the bottom-left, and a colorbar is added to indicate the values associated with the colors.
2. Overlaying Two Images Using imshow()
This example shows how to overlay two images with different colormaps and transparency using imshow().
Python
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LogNorm
dx, dy = 0.015, 0.05
x = np.arange(-4.0, 4.0, dx)
y = np.arange(-4.0, 4.0, dy)
X, Y = np.meshgrid(x, y)
extent = np.min(x), np.max(x), np.min(y), np.max(y)
Z1 = np.add.outer(range(8), range(8)) % 2
plt.imshow(Z1, cmap ="binary_r", interpolation ='nearest',
extent = extent, alpha = 1)
def geeks(x, y):
return (1 - x / 2 + x**5 + y**6) * np.exp(-(x**2 + y**2))
Z2 = geeks(X, Y)
plt.imshow(Z2, cmap ="Greens", alpha = 0.7,
interpolation ='bilinear', extent = extent)
plt.title('matplotlib.pyplot.imshow() function Example', fontweight ="bold")
plt.show()
Output

Explanation: This code generates two 2D datasets: one using a simple mathematical function (Z1) and another using a custom function (geeks(x, y)). The first dataset (Z1) is displayed with a binary colormap, and the second dataset (Z2) is displayed on top with a Greens colormap and some transparency.
Similar Reads
Python Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced
Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions
Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs
Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Enumerate() in Python
enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Data Types
Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Python Introduction
Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Input and Output in Python
Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read