How to change imshow aspect ratio in Matplotlib?
Aspect ratio is the ratio of height to width of the image we want to display. Matplotlib provides us with the feature of modifying the aspect ratio of our image by specifying the value for the optional aspect ratio attribute for our image plot. In this article, we will see how to adjust aspect ratio of image Matplotlib in Python.
Python pyplot.imshow aspect Syntax
Syntax: pyplot.imshow(image, aspect=’value’)
We can replace the value for the aspect ratio with ‘equal’, ‘auto’, or any float value representing the desired aspect ratio. In this article, we have used the below image to demonstrate the changes in aspect ratio using Matplotlib.
Change Imshow Aspect Ratio in Matplotlib
Below are some examples by which we can see how to adjust the aspect ratio of image Matplotlib in Python:
Example 1: Adjusting Aspect Ratio for an Image
In this example, an image of a chessboard is read using OpenCV and then displayed in a Matplotlib subplot with varying aspect ratios, demonstrating how different ratios can distort or stretch the image dimensions. By this example we can see how to adjust aspect ratio of image matplotlib in Python.
Python3
import matplotlib.pyplot as plt import cv2 # reading image from directory im = cv2.imread( "C://Users/User/Downloads/chess5.png" ) # plotting a figure for showing all # images in a single plot fig = plt.figure(figsize = ( 4 , 4 )) # plotting each matplot image with # different aspect ratio parameter values # in a separate subplot ax1 = fig.add_subplot( 2 , 2 , 1 ) ax1.set_xlabel( 'Original' ) # plot the initial image as the first image plt.imshow(im) ax2 = fig.add_subplot( 2 , 2 , 2 ) ax2.set_xlabel( 'Aspect Ratio : Auto' ) # plot the image with "auto" aspect ratio # as the second image plt.imshow(im, aspect = 'auto' ) ax3 = fig.add_subplot( 2 , 2 , 3 ) ax3.set_xlabel( 'Aspect Ratio : 0.5' ) # plot the image with "0.5" aspect ratio # as the third image plt.imshow(im, aspect = '0.5' ) ax4 = fig.add_subplot( 2 , 2 , 4 ) ax4.set_xlabel( 'Aspect Ratio : 1.5' ) # plot the image with "1.5" aspect ratio # as the fourth image plt.imshow(im, aspect = '1.5' ) # display the plot plt.show() |
Output:
Example 2: Adjusting Aspect Ratio for a Plot
In this example, a simple plot of data points is created using Matplotlib. The aspect ratio is then adjusted to ensure that the visual representation maintains a consistent scale along both the x and y axes.
Python3
import matplotlib.pyplot as plt # Sample data for plotting x = [ 1 , 2 , 3 , 4 , 5 ] y = [ 2 , 4 , 6 , 8 , 10 ] # Plotting plt.plot(x, y) plt.title( 'Plot with Aspect Ratio Adjustment' ) # Setting aspect ratio to 1 plt.gca().set_aspect( 1 ) plt.show() |
Output:
Contact Us