How do I change the size of figures drawn with Matplotlib?
To swiftly adjust the Matplotlib figure size, use the figsize
parameter when creating the figure. Set width and height in inches:
And in the case of 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:
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:
To save your figure in high-resolution, use the savefig
function:
Resizing figures dynamically and setting global defaults
Already created a figure but need to resize it? Do dynamic resizing after creation as follows:
For a consistent style across all your figures, you can define a global default size:
To convert measurements from centimeters to inches for figsize
, divide by 2.54 (thanks, math!):
And to revert back to Matplotlib defaults:
Adjusting figure size with pandas
When generating plots directly from a Pandas DataFrame, you can specify the figure size:
Or resize axes when plotting with pandas:
More info on Pandas DataFrame plotting is available here.
Handling subplots and complex layouts
In cases with multiple subplots, each needing a unique size:
For plots that require fine-grained configurations, Gridspec is your friend:
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 thesubplot
creation parameterconstrained_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 adjustsys.displayhook.figsize
.
And, always remember, when in doubt, come back to this guide!
Was this article helpful?