Home >Backend Development >Python Tutorial >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
<code class="python">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')</code>
By using axis('off') and bbox_inches='tight' together, we can effectively remove all axes, legends, and white padding, leaving only the desired image.
The above is the detailed content of How to Remove Axes, Legends, and White Padding in Matplotlib?. For more information, please follow other related articles on the PHP Chinese website!