How Do I Change the Figure Size of Figures Drawn With Matplotlib?

How Do I Change The Size Of Figures Drawn With Matplotlib

One of the key fields where Python shines is Data Science, with no other language there that stands out like Python. And at the heart of it stands Matplotlib, an amazing library for creating all kinds of visuals of the data. Along with numPy, Pandas, SciPy, and many more, it lays down the basis of data science in the most easiest way possible.

The Matplotlib library provides a lot of flexibility in creating graphs and designs. It allows you to control every aspect of the visual you create. An important feature is its ability to change the figure size. There are many ways in which you can achieve this.

In this article, we’re going to dive deep into the world of data science and explore the matplotlib library. On our way, we’re going to check different ways in which you can change the size of figures drawn with matplotlib. So let’s get started.

Plotting a simple scatter plot using Matplotlib

A scatter plot is a simplistic 2-dimensional graph. It’s very common, well-known, and really powerful. Let’s try to create a scatter plot using Matplotlib.

We’re going to create the scatter plot based on a dataframe that we created in one of the previous articles. If you don’t know how to create a dataframe, make sure to check out this article where we learn to create a dataframe.

import pandas as pd
data = pd.read_csv( "example.csv" )
data
Sample Dataset
Sample Dataset

Now that we have our dataframe ready, we can proceed to plot the scatter plot.

import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_csv("example.csv")
plt.scatter(data['Programming language'], data['Foundation year'])
plt.title("Programming language-Foundation year scatter plot")
plt.xlabel("Programming language")
plt.ylabel("Foundation year")
plt.show()

To plot the graph, we’re going to use the pyplot module of the Matplotlib library. First, we read the CSV file and store the data in a dataframe using the pandas library. After that, plot the scatter plot using matplotlib.pyplot.scatter() which takes 2 arguments – the X-axis and the Y-axis. We passed programming language as the X-axis and Foundation year as the Y-axis. Then we set the title and labels of the axes. In the end, we used the plt.show() method to display the actual graph.

Scatter Plot Programming Language Foundation Year
Scatter Plot Programming Language Foundation Year

There we go. We can make a beautiful and simple scatter plot. Well, we can clearly understand that Python was invented in 1991 seeing this, so yeah, we did it.

Default figure size in Matplotlib

The size of this graph produced using the matplotlib.pyplot module has a default size of 6.4×4.8 inches. That means it has a height of 4.8 inches and a width of 6.4 inches.

Figure size of the figure
Figure size of the figure

This size is standard for any graph produced by the matplotlib library. It fits perfectly on a standard computer screen. But sometimes, we may need to change the size of this figure.

There are a number of ways in which you can change the size of the figure. Let’s check a few of them one by one.

Changing figure size using figsize argument

When you plot a graph, the default parameters for the figure size the 6.4×4.8 inches. The matplotlib.pylot module has a figure() method which regulates the features of the figure which will be displayed. This figure() method has a parameter figsize. The figsize parameter takes a tuple of two floats as the argument. The first float is the height, and the second one is the width of the figure which will be displayed.

We can manipulate the figure according to our convenience using this figsize parameter. Let’s see how we can do this. Let’s try to set the figure size to 4×3 inches. To do this, we just have to add the following code line before the plt.scatter line.

plt.figure(figsize = (4,3))
Change Figure Size Using Figsze Matplotlib
Change Figure Size Using Figsze Matplotlib

Using figsize() method, you can change the figure size with just one line of code. But the problem with the figsize() method is that it has to be put before plotting the graph. The set_figheight() and set_figwidth() method lets you set the figure size after plotting the graph.

Using set_figheight() and set_figwidth()

set_figheight() and set_figwidth() are the functions which can be used to set the figure size after plotting the graph.

figure = plt.gcf()
figure.set_figheight(3)
figure.set_figwidth(4) 
Change Figure Size Using Set Method
Change Figure Size Using Set Method

plt.gcf() method gets the current figure. The set_figheight() and set_figwidth() methods sets the height and width of the figure.

How to change the default size of the figure?

Matplotlib has a dictionary called rcparams which stores all the default parameters of a figure. You can access this dictionary and simply change a default parameter that you want to. So we can change the default figure size in this rcparams dictionary. You can do it just by writing the following line of code.

plt.rcParams['figure.figsize'] = (4,3)
Change Default Figure Size
Change Default Figure Size

The figure.figsize key has a tuple of 2 floats as value. We can set the value as a tuple – (<figwidth>,<figheight>).

This rcparams dictionary contains more default parameters similar to the figure size, like colors of the elements, font size of the characters, limits of the axes, and many more. You can change them according to your liking. Make sure to check the rcparams section of Matplotlib Official Documentation. It contains a detailed description of all the parameters and how you can work on them.

Contour plots in Matplotlib

Contour plots are 3-dimensional graphs which can be represented in a 2-dimensional surface. Matplotlib can also plot contour plots ad many other 3-dimensional plots. Let’s see how can we plot a contour using Matplotlib.

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
contour_plot = ax.plot_surface(X, Y, Z, cmap='viridis')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_title('Three-Dimensional Contour Plot')
fig.colorbar(contour_plot)
plt.show()
Plotting A Contour
Plotting A Contour

First, we imported the necessary packages. Then we created a series of 100 numbers from -5 to 5 using the linspace method of numpy. Then we created a grid of these numbers using the meshgrid method of numpy and stored the matrices in X and Y. After that, we generated the values of z as the sine of the square root of the sum of x squared and y squared.

Then we generated a figure using the plt.figure() function. We added a 3d subplot to this figure. Then we plotted a contour using the values of X, Y, and Z and set the color mapping as viridis. Then we set the names for axes and the title. Then we set the colour bar based on our contour.

Related: Learn how we can plot different contour plots using Matplotlib.

How to change the figure size of a contour plot?

You can change the figure size of a contour plot just like a 2d plot. All three methods apply here too. The most basic way is setting the figsize parameter in the plt.figure() function.

Changing Figure Size Of A Contou
Changing Figure Size Of A Contou

Seaborn vs. Matplotlib – which is better?

Seaborn is also a visualization library similar to Matplotlib built on top of Matplotlib. It has great capabilities for statistical visualizations. It is simple to use and can be used to directly generate graphs out of a dataframe. But when it comes to flexibility, Matplotlib beats Seaborn. Matplotlib provides a lot of customization abilities and flexibility to create any kind of graph.

Both Seaborn and Matplotlib are amazing libraries but have their usage. You must know when to use which one.

Conclusion

Matplotlib is an amazing library that brings Python to the right standards. It makes data science much easier. It helps you create awesome visuals which can be customized and manipulated very easily. We need to keep exploring the Matplotlib library as it has so many functionalities which can’t be just learnt in a few weeks.

References

Official Matplotlib Documentation

Stack Overflow answer on the same question.