Matplotlib: Change Width & Height of a Figure with Subplots

Last updated on December 6, 2021 The Plumber Loading... Post a comment

When using Matplotlib to create a figure that contains a grid of subplots, you can set the width and height of the figure by using the set_figwidth() and set_figheight() methods, respectively. Let’s examine the two examples below for more clarity.

Example 1

This example creates a figure with two subplots, side by side. The width is set to 20 and the height is set to 8:

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(facecolor='orange')
fig.set_figwidth(20)
fig.set_figheight(8)
ax1 = fig.add_subplot(1, 2, 1)
ax2 = fig.add_subplot(1, 2, 2)

np.random.seed(0)
ax1.hist(np.random.randn(100), bins=30, color='indigo', alpha=0.4)
ax2.scatter(np.arange(30), np.arange(30) * np.arange(30))

Output:

Example 2

This example creates a figure with four subplots:

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
fig.set_figwidth(20)
fig.set_figheight(8)
ax1 = fig.add_subplot(2, 2, 1)
ax2 = fig.add_subplot(2, 2, 2)
ax3 = fig.add_subplot(2, 2, 3)
ax4 = fig.add_subplot(2, 2, 4)

np.random.seed(1)
ax1.hist(np.random.randn(100), bins=30, color='blue', rwidth=0.5)
ax2.scatter(np.arange(30), np.arange(30) * np.arange(30))
ax3.plot(np.random.randn(30).cumsum(), 'red')
ax4.scatter(np.arange(30), np.arange(30) + np.random.randn(30) * 2.5)

Output:

Further reading:

You can also check out our Python category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like