Home >Backend Development >Python Tutorial >How to Remove Axes, Legends, and White Padding in Matplotlib Plots?
Eliminating Axes, Legends, and White Padding in Matplotlib
To create a clean image without distracting elements, it's crucial to remove axes, labels, and white padding from Matplotlib plots. While setting the axis visibility to False resolves the axis issue, it leaves behind a white border and padding.
Addressing White Padding
To eliminate the white padding surrounding the image, you can employ the bbox_inches parameter when saving the image. Setting it to 'tight' will crop the figure boundaries to the extent of the data, reducing white space significantly.
Newer Matplotlib Versions
Note that for newer Matplotlib versions, you may need to use bbox_inches=0 instead of 'tight' to achieve the same result. This ensures that the image is saved with no margins or padding whatsoever.
Example Code
Here's an updated code snippet that implements the above fixes:
<code class="python">from numpy import random import matplotlib.pyplot as plt data = random.random((5, 5)) img = plt.imshow(data, interpolation='nearest') img.set_cmap('hot') plt.axis('off') plt.savefig("test.png", bbox_inches=0)</code>
Output
The resulting image will be free of axes, labels, white padding, and frame, providing a clean and focused representation of your data.
The above is the detailed content of How to Remove Axes, Legends, and White Padding in Matplotlib Plots?. For more information, please follow other related articles on the PHP Chinese website!