Home  >  Article  >  Backend Development  >  How to Eliminate Axis, Legends, and White Padding in Matplotlib Image Save?

How to Eliminate Axis, Legends, and White Padding in Matplotlib Image Save?

Linda Hamilton
Linda HamiltonOriginal
2024-10-23 22:46:02814browse

How to Eliminate Axis, Legends, and White Padding in Matplotlib Image Save?

Eliminating Axis, Legends, and White Padding in Matplotlib Image Save

Problem:

When using Matplotlib to color-map and save an image, unwanted elements such as axes, labels, and white padding may appear around the actual image.

Solution:

To address these issues, consider the following modifications:

  • Disable Axis Visibility:

    • Use plt.axis('off') to hide both x and y axes simultaneously.
  • Remove White Padding:

    • Add bbox_inches='tight' to the savefig command. This adjusts the bounding box to fit the image closely, reducing or eliminating white space.

Example:

<code class="python">import numpy as np
import matplotlib.pyplot as plt

data = np.random.random((5, 5))
img = plt.imshow(data, interpolation='nearest')
img.set_cmap('hot')
plt.axis('off')
plt.savefig("test.png", bbox_inches='tight')</code>

This approach effectively removes axes, legend, and white padding, leaving only the desired color-mapped image.

Note: Newer versions of Matplotlib may require using bbox_inches=0 instead of the string 'tight'.

The above is the detailed content of How to Eliminate Axis, Legends, and White Padding in Matplotlib Image Save?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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