"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Save a Matplotlib Figure with Exact Pixel Dimensions?

How to Save a Matplotlib Figure with Exact Pixel Dimensions?

Published on 2024-11-09
Browse:352

How to Save a Matplotlib Figure with Exact Pixel Dimensions?

Specifying and Saving a Figure with Exact Size in Pixels

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:

  1. Divide the desired pixel width and height by your monitor's DPI:

    figsize = (800 / my_dpi, 800 / my_dpi)
  2. Create a figure with the calculated size and DPI:

    plt.figure(figsize=figsize, dpi=my_dpi)
  3. 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:

  • Some backend formats (e.g., PDF, PS) may handle figure sizes differently.
  • Changing DPI and sizes also affects other aspects, like font size.
  • For large image sizes, there may be a slight discrepancy between the requested and saved DPI.
Latest tutorial More>

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