Specifying and saving a figure with exact size in pixels
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
Matplotlib specifies figure sizes in inches and DPI (dots per inch), not pixels directly. To save a figure with exact pixel dimensions, you need to set the figure size in inches and the DPI such that their product equals the desired pixel count. For example, an 800x600 pixel image at 100 DPI requires an 8x6 inch figure.
The Formula
For 800x600 pixels at 100 DPI:
- Width: 800 / 100 = 8 inches
- Height: 600 / 100 = 6 inches
Basic Approach
The saved plot.png will be exactly 800x600 pixels.
Helper Function
Create a reusable function for pixel-exact figures:
Matching DPI on Save
The DPI must match between figure creation and saving. A mismatch produces the wrong pixel dimensions:
Removing Padding and Margins
Matplotlib adds padding around the plot by default. To get exact pixel dimensions with no extra whitespace:
Note: bbox_inches='tight' adjusts the bounding box to fit content, which may change the actual pixel size. For strict pixel control, set margins manually instead:
High-DPI (Retina) Figures
For Retina displays, use higher DPI:
Working with Different File Formats
Different formats handle DPI settings differently:
Verifying Pixel Dimensions
Or from the command line:
Multiple Subplots with Exact Size
Common Pitfalls
- DPI Matching: Always ensure that the DPI specified during figure creation is matched when saving the figure. A mismatch can lead to incorrect pixel dimensions.
- Aspect Ratio: Check that altering dimensions does not unintentionally distort your graphical elements. Use
ax.set_aspect('equal')for square axes. - File Formats: Different formats (PNG, TIFF, etc.) may handle scaling and DPI settings differently. PNG is generally recommended for maintaining pixel accuracy.
- bbox_inches='tight': This option recalculates the bounding box based on content, which overrides your specified figure size. Avoid it when exact pixel dimensions matter.
- Interactive display vs save:
plt.show()may render at screen DPI, which differs from your save DPI. The saved file has the correct dimensions; the interactive display may differ. - Backend differences: Some Matplotlib backends (Agg, Cairo) may produce slightly different results. The Agg backend is the default and most reliable for PNG output.
Summary
- Set figure size in inches = desired pixels / DPI:
figsize=(px/dpi, py/dpi) - Always use the same DPI for creation and saving:
fig.savefig('out.png', dpi=fig.dpi) - Use PNG format for pixel-accurate output
- Avoid
bbox_inches='tight'when exact dimensions are critical - Verify output dimensions with PIL or ImageMagick
Related reading
- Split / Explode a column of dictionaries into separate columns with pandas
- Split a dataset created by Tensorflow dataset API in to Train and Test?
- Split a large pandas dataframe
- Split a Pandas column of lists into multiple columns
- Split data directory into training and test directory with sub directory structure preserved
- Split explode pandas dataframe string entry to separate rows
- Splitting a tensorflow dataset into training, test, and validation sets from keras.preprocessing API
- Splitting values into groups evenly
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.