How to Hide Axis, Borders and White Spaces in Matplotlib
This tutorial explains how to hide the axis in the plot using the matplotlib.pyplot.axis('off')
command and how to remove all the whitespaces, and borders in the figure while saving the figure.
Hide the Axis in Matplotlib Figure
To hide the axis, we can use the command matplotlib.pyplot.axis('off')
.
import numpy as np
import matplotlib.pyplot as plt
img = np.random.randn(10, 10)
plt.imshow(img)
plt.axis("off")
plt.show()
Output:
It hides both the X-axis and Y-axis in the figure.
If we just want to turn either the X-axis or Y-axis off, we can use axes.get_xaxis().set_visible()
or axes.get_xaxis().set_visible()
method respectively.
import numpy as np
import matplotlib.pyplot as plt
img = np.random.randn(10, 10)
fig = plt.imshow(img)
ax = plt.gca()
ax.get_xaxis().set_visible(False)
plt.show()
Output:
It only hides the X-axis in the figure.
Hide the Whitespaces and Borders in Matplotlib Figure
The plt.axis('off')
command hides the axis, but we get whitespaces around the image’s border while saving it. To get rid of whitespace around the border, we can set bbox_inches='tight'
in the savefig()
method. Similarly, to remove the white border around the image while we set pad_inches = 0
in the savefig()
method.
import numpy as np
import matplotlib.pyplot as plt
img = np.random.randn(10, 10)
fig = plt.imshow(img)
plt.axis("off")
plt.savefig("image.png", bbox_inches="tight", pad_inches=0)
Saved Image:
It saves the images without any axis, borders, and whitespaces using the savefig()
method.
We can also save the image without axis, borders, and whitespace using the matplotlib.pyplot.imsave()
method.
import numpy as np
import matplotlib.pyplot as plt
img = np.random.randn(100, 100)
plt.imsave("kapal.png", img)
Suraj Joshi is a backend software engineer at Matrice.ai.
LinkedIn