"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 Remove Axes, Legends, and White Padding in Matplotlib?

How to Remove Axes, Legends, and White Padding in Matplotlib?

Posted on 2025-03-23
Browse:161

How to Remove Axes, Legends, and White Padding in Matplotlib?

Removing Axes, Legends, and White Padding in Matplotlib

In this article, we address the issue of removing axes, legends, and white padding when saving an image generated using Matplotlib.

Removing Axes

The original code snippet successfully removes the axes of the figure by hiding the x-axis and y-axis using fig.axes.get_xaxis().set_visible(False) and fig.axes.get_yaxis().set_visible(False), respectively. However, this technique may not entirely resolve the issue of white padding and frame around the image.

Removing White Padding

To remove the white padding, we can use the axis('off') method, which hides all axes and borders, leaving only the image itself. However, this method may still leave a small amount of white space around the image.

To further eliminate the white padding, we can add bbox_inches='tight' to the savefig command. This will crop the saved image to the exact size of the image data, leaving no white space around the borders.

Updated Code Snippet

def make_image(inputname,outputname):
    data = mpimg.imread(inputname)[:,:,0]
    fig = plt.imshow(data)
    fig.set_cmap('hot')
    plt.axis('off')
    plt.savefig(outputname, bbox_inches='tight')

By using axis('off') and bbox_inches='tight' together, we can effectively remove all axes, legends, and white padding, leaving only the desired image.

Release Statement This article is reproduced on: 1729668289 If there is any infringement, please contact [email protected] to delete it.
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