How to Remove White Space Around Saved Images in Matplotlib?

Linda Hamilton
Release: 2024-11-06 15:59:02
Original
248 people have browsed it

How to Remove White Space Around Saved Images in Matplotlib?

Removing White Space Around Saved Images

When saving images after processing, it's common to encounter white space padding around the image. This can be frustrating, especially if youต้องการ a clean, cropped image.

For the snippet you provided:

<code class="python">fig = plt.figure(1)
img = mpimg.imread("image.jpg")
plt.imshow(img)
ax = fig.add_subplot(1, 1, 1)

extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
plt.savefig('1.png', bbox_inches=extent)</code>
Copy after login

Using tight= to savefig() does not solve the white space issue. Instead, try setting bbox_inches as a string:

<code class="python">plt.savefig("test.png", bbox_inches='tight')</code>
Copy after login

This should remove the white space padding, giving you a clean, cropped image.

Additionally, when using NetworkX to draw graphs on the figure, you may encounter white space around the saved image. To prevent this, ensure that bbox_inches="tight" is set in savefig().

Possible Duplicates:

  • Matplotlib plots: removing axis, legends, and white spaces: Focuses on removing various elements from plots, including white space.
  • How to set the margins for a matplotlib figure?: Provides in-depth information on setting margins, including removing white space.
  • Reduce left and right margins in matplotlib plot: Specifically addresses reducing margins around plots.

The above is the detailed content of How to Remove White Space Around Saved Images in Matplotlib?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template