Set the aspect ratio in Matplotlib in Python
Learn how to set the aspect ration in Matplotlib in Python.
Setting the aspect ratio in the program is essential to adjust the dimension of the graph without changing the contents.
In Python, we use Matplotlib to create and maintain the graph with its various parameters.
Whats is Matplotlib?
The matplotlib is the library in the python for the visualization of plotting 2D array.
Matplotlib is the data visualization source which also implies that data will be visualized in the desirable 2D Array plot.
Uses of the Matplotlib?
The most known and huge advantage of the matplotlib is that it can also be used to digest large data and maintain to convert in various types of plots similarly a line graph, Histogram, Bar Graph, Scatter Diagram and many more…
What is the aspect ratio in the matplotlib?
In fact, there is 4 co-ordinate system in Matplotlib. Which is generally classified into data, axes, figure, display.
The actual Y-axis is divided by the actual X-axis and that refers to the method set_aspect() i.e If the aspect ratio is equal to 1 then the X-axis and Y-axis are the same lengths.
Setting the aspect ratio of the Matplotlib plot in Python
As we are working on a graph we must focus on the division of both co-ordinates which is X and Y.
The method set_aspect() is used to set the aspect ratio. The parameter of this method is a number which is a division of the X-axis with respect to the Y-axis.
The aim is to achieve a precise and ideal ratio by traversing the values of X and Y
This example will clear the idea of the aspect ratio of the plotted graph
We are taking a line plot using plot()
1] With no fixed aspect ratio
import matplotlib.pyplot as plt import numpy as np #Setting the axes. x = np.arange(1,5,0.2) y = np.sin(7*x) #Setting the Dimentions of the Graph plt.figure(figsize = (5,5)) plt.plot(x,y) plt.title('plot with undefined aspect ratio') plt.show()
The Output is as below
After making changes and setting the absolute aspect ratio. Even the figure size is the same!
import matplotlib.pyplot as plt import numpy as np #Setting the axes. x = np.arange(1,5,0.2) y = np.sin(7*x) #Setting the Dimentions of the Graph plt.figure(figsize = (5,5)) #selecting the current axis ax = plt.gca() #sets the ratio to 5 ax.set_aspect(5) plt.plot(x,y) plt.title('plot with defined aspect ratio') plt.show()
The Output is as below
The ratio is set and without changing the content of the size of the graph.