Explain Codes LogoExplain Codes Logo

How do I change the size of figures drawn with Matplotlib?

python
matplotlib
data-visualization
pandas
Alex KataevbyAlex Kataev·Aug 10, 2024
TLDR

To swiftly adjust the Matplotlib figure size, use the figsize parameter when creating the figure. Set width and height in inches:

plt.figure(figsize=(10, 8)) # As wide as a pancake, as tall as a short cake.

And in the case of subplots:

fig, ax = plt.subplots(figsize=(10, 8)) # Twice the fun for your subplots!

Remember, this should be done before plotting data to ensure the new size applies correctly.

Enhancing figure resolution

To boost your figure's resolution, fiddle with the dpi (dots per inch). This becomes crucial when you're preparing figures for print or a high-resolution display:

plt.figure(figsize=(10, 8), dpi=120) # Crisp and clear like a chilly winter morning.

Matplotlib default dpi is typically set to 80. Increasing this value leads to high-quality images, albeit larger in size. A dpi value of 300 or more is generally recommended in the print industry:

fig = plt.gcf() # Grabs currently active figure fig.set_dpi(120) # Sets sharper dpi, because clarity counts.

To save your figure in high-resolution, use the savefig function:

plt.savefig('high_res_fig.png', dpi=150) # Save figure with precise resolution, because details matter.

Resizing figures dynamically and setting global defaults

Already created a figure but need to resize it? Do dynamic resizing after creation as follows:

fig = plt.gcf() # Get the current figure fig.set_size_inches(12, 10, forward=True) # Suddenly, the canvas becomes a mighty billboard.

For a consistent style across all your figures, you can define a global default size:

plt.rcParams["figure.figsize"] = (10, 8) # All figures report for resizing!

To convert measurements from centimeters to inches for figsize, divide by 2.54 (thanks, math!):

width_in = 20 / 2.54 # Width from cms to ins height_in = 25 / 2.54 # Height from cms to ins plt.figure(figsize=(width_in, height_in)) # Welcome to the land of inches.

And to revert back to Matplotlib defaults:

plt.rcParams["figure.figsize"] = plt.rcParamsDefault["figure.figsize"] # Back to basics.

Adjusting figure size with pandas

When generating plots directly from a Pandas DataFrame, you can specify the figure size:

df['column'].plot(figsize=(12, 9)) # Because pandas also need space to roam.

Or resize axes when plotting with pandas:

fig, ax = plt.subplots(figsize=(10,5)) # Predefine the axes df['column'].plot(ax=ax) # Plot to these axes ax.set_size_inches(12, 9) # Allow pandas to spread its wings

More info on Pandas DataFrame plotting is available here.

Handling subplots and complex layouts

In cases with multiple subplots, each needing a unique size:

fig, axarr = plt.subplots(2, 2, figsize=(20, 15)) # Sized and ready for action.

For plots that require fine-grained configurations, Gridspec is your friend:

from matplotlib import gridspec gs = gridspec.GridSpec(2, 2) # Ready, set, grid! ax1 = plt.subplot(gs[0, :]) # Top row, all columns ax2 = plt.subplot(gs[1, :-1]) # Bottom row, first column ax3 = plt.subplot(gs[1:, -1]) # Bottom row, last column

Troubleshooting tips

When adjusting figure sizes, be sure to mind the following:

  • Aspect Ratios: Ensure ratio doesn't distort your data!
  • Overlapping elements: Prevent cut-off labels with tight_layout() or the subplot creation parameter constrained_layout=True.
  • Quality drop in print: Check whether the dpi is high enough for good quality prints (e.g., dpi = 300).
  • Inline display size in Jupyter notebooks: Use %matplotlib inline and adjust sys.displayhook.figsize.

And, always remember, when in doubt, come back to this guide!