Home > Article > Backend Development > How to Save a Matplotlib Figure with Exact Pixel Dimensions?
When saving a matplotlib figure, it can be desirable to specify the exact size of the resulting image in pixels, without specifying the dimensions in inches or relying on screen DPI conversions.
Matplotlib's Limitations
Matplotlib primarily uses physical sizes (inches) and DPI to control figure dimensions. However, to display a figure in a specific pixel size, the screen DPI must be known.
Determining Screen DPI
Various methods exist to determine the DPI of your monitor. For example, the following link provides an online tool: [Detect Your Monitor's DPI](https://screenresolution.info/screen-dpi.php)
Generating and Saving a Specific Pixel Size Image
To generate and save a figure with a specific pixel size (e.g., 800x800 pixels), use the following steps:
Divide the desired pixel width and height by your monitor's DPI:
figsize = (800 / my_dpi, 800 / my_dpi)
Create a figure with the calculated size and DPI:
plt.figure(figsize=figsize, dpi=my_dpi)
Save the figure using matplotlib.pyplot.savefig() with the desired DPI:
plt.savefig('my_fig.png', dpi=my_dpi)
Saving a Larger Image
If you want to save an image with a higher resolution than your screen DPI, you can specify a higher DPI value in savefig():
plt.savefig('my_fig.png', dpi=my_dpi * 10)
Note:
The above is the detailed content of How to Save a Matplotlib Figure with Exact Pixel Dimensions?. For more information, please follow other related articles on the PHP Chinese website!