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:
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3