Change plot size in Matplotlib – Python
Last Updated :
10 Jan, 2024
Plots are an effective way of visually representing data and summarizing it beautifully. However, if not plotted efficiently it seems appears complicated. Python’s Matplotlib provides several libraries for data representation. While making a plot we need to optimize its size. In this article, we will explore the process of steps to set the size of the plot in Matplotlib or adjust the plot size in Matplotlib by examining various examples and methodologies.
Change Plot Size in Matplotlib in Python
There are various ways we can use those steps to set size of plot in Matplotlib in Python:
Change the Size of Figures using set_figheight() and set_figwidth()Â
In this example, the code uses Matplotlib to create two line plots. The first plot is created with default size, displaying a simple line plot. The second plot is created after adjusting the figure size (width: 4, height: 1), showcasing how to change the dimensions of the plot. The `plt.show()` function is used to display each plot.
Python3
import matplotlib.pyplot as plt
x = [ 1 , 2 , 3 , 4 , 5 ]
y = [ 1 , 2 , 3 , 4 , 5 ]
plt.xlabel( 'x - axis' )
plt.ylabel( 'y - axis' )
print ( "Plot in it's default size: " )
plt.plot(x, y)
plt.show()
f = plt.figure()
f.set_figwidth( 4 )
f.set_figheight( 1 )
print ( "Plot after re-sizing: " )
plt.plot(x, y)
plt.show()
|
Output:
Changing Plot Size in Matplotlib using figsize()
figsize takes two parameters- width and height (in inches). By default the values for width and height are 6.4 and 4.8 respectively.Â
Syntax:
plt.figure(figsize=(x,y))Â
Where, x and y are width and height respectively in inches. In this example code uses Matplotlib to create two line plots. The first plot is displayed in the default size, and the second plot is shown after changing the figure size to 2×2 using `plt.figure(figsize=(2, 2))`.
Python3
import matplotlib.pyplot as plt
x = [ 1 , 2 , 3 , 4 , 5 ]
y = [ 6 , 7 , 8 , 9 , 10 ]
display(plt.plot(x, y))
plt.figure(figsize = ( 2 , 2 ))
display(plt.plot(x, y))
|
Output:
output screenshot
Python Change Plot Size in Matplotlib Using Default rcParams
We can permanently change the default size of a figure as per our needs by setting the figure.figsize. In this example, we are using Matplotlib to create a line plot with the default size and then adjusts the default figure size to [2, 2]. It subsequently produces both a line plot and a scatter plot with the modified figure size.
Python3
import matplotlib.pyplot as plt
x = [ 1 , 2 , 3 , 4 , 5 ]
y = [ 1 , 2 , 3 , 4 , 5 ]
plt.xlabel( 'x - axis' )
plt.ylabel( 'y - axis' )
plt.plot(x, y)
plt.show()
plt.rcParams[ 'figure.figsize' ] = [ 2 , 2 ]
plt.plot(x, y)
plt.show()
plt.scatter(x, y)
plt.show()
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...