670

How do I increase the figure size for this figure?

This does nothing:

f.figsize(15, 15)

Example code from the link:

import matplotlib.pyplot as plt
import numpy as np

# Simple data to display in various forms
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)

plt.close('all')

# Just a figure and one subplot
f, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')

# Two subplots, the axes array is 1-d
f, axarr = plt.subplots(2, sharex=True)
axarr[0].plot(x, y)
axarr[0].set_title('Sharing X axis')
axarr[1].scatter(x, y)

# Two subplots, unpack the axes array immediately
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
ax1.plot(x, y)
ax1.set_title('Sharing Y axis')
ax2.scatter(x, y)

# Three subplots sharing both x/y axes
f, (ax1, ax2, ax3) = plt.subplots(3, sharex=True, sharey=True)
ax1.plot(x, y)
ax1.set_title('Sharing both axes')
ax2.scatter(x, y)
ax3.scatter(x, 2 * y ** 2 - 1, color='r')
# Fine-tune figure; make subplots close to each other and hide x ticks for
# all but bottom plot.
f.subplots_adjust(hspace=0)
plt.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=False)

# row and column sharing
f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex='col', sharey='row')
ax1.plot(x, y)
ax1.set_title('Sharing x per column, y per row')
ax2.scatter(x, y)
ax3.scatter(x, 2 * y ** 2 - 1, color='r')
ax4.plot(x, 2 * y ** 2 - 1, color='r')

# Four axes, returned as a 2-d array
f, axarr = plt.subplots(2, 2)
axarr[0, 0].plot(x, y)
axarr[0, 0].set_title('Axis [0,0]')
axarr[0, 1].scatter(x, y)
axarr[0, 1].set_title('Axis [0,1]')
axarr[1, 0].plot(x, y ** 2)
axarr[1, 0].set_title('Axis [1,0]')
axarr[1, 1].scatter(x, y ** 2)
axarr[1, 1].set_title('Axis [1,1]')
# Fine-tune figure; hide x ticks for top plots and y ticks for right plots
plt.setp([a.get_xticklabels() for a in axarr[0, :]], visible=False)
plt.setp([a.get_yticklabels() for a in axarr[:, 1]], visible=False)

# Four polar axes
f, axarr = plt.subplots(2, 2, subplot_kw=dict(projection='polar'))
axarr[0, 0].plot(x, y)
axarr[0, 0].set_title('Axis [0,0]')
axarr[0, 1].scatter(x, y)
axarr[0, 1].set_title('Axis [0,1]')
axarr[1, 0].plot(x, y ** 2)
axarr[1, 0].set_title('Axis [1,0]')
axarr[1, 1].scatter(x, y ** 2)
axarr[1, 1].set_title('Axis [1,1]')
# Fine-tune figure; make subplots farther from each other.
f.subplots_adjust(hspace=0.3)

plt.show()
1

6 Answers 6

1204

Use .set_figwidth and .set_figheight on the matplotlib.figure.Figure object returned by plt.subplots(), or set both with f.set_size_inches(w, h).

f.set_figheight(15)
f.set_figwidth(15)

Note: Unlike set_size_inches(), where the measurement unit is explicitly mentioned in the function's name, this is not the case for set_figwidth() and set_figheight(), which also use inches. This information is provided by the documentation of the function.

Alternatively, when using .subplots() to create a new figure, specify figsize=:

f, axs = plt.subplots(2, 2, figsize=(15, 15))

.subplots accepts **fig_kw, which are passed to pyplot.figure, and is where figsize can be found.

Setting the figure's size may trigger the ValueError exception:

Image size of 240000x180000 pixels is too large. It must be less than 2^16 in each direction

This is a common problem for using the set_fig*() functions due to the assumptions that they work with pixels and not inches (obviously 240000*180000 inches is too much).

99

In addition to the previous answers, here is an option to set the size of the figure and the size of the subplots within the figure individually by means of gridspec_kw:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

#generate random data
x,y=range(100), range(10)
z=np.random.random((len(x),len(y)))
Y=[z[i].sum() for i in range(len(x))]
z=pd.DataFrame(z).unstack().reset_index()

#Plot data
fig, axs = plt.subplots(2,1,figsize=(16,9), gridspec_kw={'height_ratios': [1, 2]})
axs[0].plot(Y)
axs[1].scatter(z['level_1'], z['level_0'],c=z[0])

with this figure as result: enter image description here

0
70

Alternatively, create a figure() object using the figsize argument and then use add_subplot to add your subplots. E.g.

import matplotlib.pyplot as plt
import numpy as np

f = plt.figure(figsize=(10,3))
ax = f.add_subplot(121)
ax2 = f.add_subplot(122)
x = np.linspace(0,4,1000)
ax.plot(x, np.sin(x))
ax2.plot(x, np.cos(x), 'r:')

Simple Example

Benefits of this method are that the syntax is closer to calls of subplot() instead of subplots(). E.g. subplots doesn't seem to support using a GridSpec for controlling the spacing of the subplots, but both subplot() and add_subplot() do.

10

You can use plt.figure(figsize = (16,8)) to change figure size of a single plot and with up to two subplots. (arguments inside figsize lets to modify the figure size)

To change figure size of more subplots you can use plt.subplots(2,2,figsize=(10,10)) when creating subplots.

6

For plotting subplots in a for loop which is useful sometimes: Sample code to for a matplotlib plot of multiple subplots of histograms from a multivariate numpy array (2 dimensional).

plt.figure(figsize=(16, 8)) 
for i in range(1, 7):
    plt.subplot(2, 3, i)
    plt.title('Histogram of {}'.format(str(i)))
    plt.hist(x[:,i-1], bins=60)
1

Instead of via gridspec_kw, height_ratios/width_ratios can be passed to plt.subplots as kwargs since matplotlib 3.6.0. So the relative height can be set as follows.

import matplotlib.pyplot as plt
import random
data = random.sample(range(100), k=100)

fig, axs = plt.subplots(2, figsize=(6,4), height_ratios=[1, 2])
#                                         ^^^^^^^^^  <---- here
axs[0].plot(data)
axs[1].scatter(range(100), data, s=10);

result1


However, if it's desired to draw subplots of differing sizes, one way is to use matplotlib.gridspec.GridSpec but a much simpler way is to pass appropriate positions to add_subplot() calls. In the following example, first, the first subplot in a 2x1 layout is plotted. Then instead of plotting in the second subplot of the 2x1 layout, initialize a 2x2 layout but plot in its third subplot (the space for the first two subplots in this layout is already taken by the top plot).

fig = plt.figure(figsize=(6, 4))

ax1 = fig.add_subplot(2, 1, 1)      # initialize the top Axes
ax1.plot(data)                      # plot the top graph

ax2 = fig.add_subplot(2, 2, 3)      # initialize the bottom left Axes
ax2.scatter(range(100), data, s=10) # plot the bottom left graph

ax3 = fig.add_subplot(2, 2, 4)      # initialize the bottom right Axes
ax3.plot(data)                      # plot the bottom right graph

result2


Finally, if it's needed to make a subplot of a custom size, one way is to pass (left, bottom, width, height) information to a add_axes() call on the figure object.

fig = plt.figure(figsize=(6,4))
ax1 = fig.add_axes([0.05, 0.6, 0.9, 0.25])  # add the top Axes
ax1.plot(data)                              # plot in the top Axes
ax2 = fig.add_axes([0.25, 0, 0.5, 0.5])     # add the bottom Axes
ax2.scatter(range(100), data, s=10);        # plot in the bottom Axes

result3

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.