Reputation: 1524
Other answers on this site discuss how to remove "whitespace" margins around matplotlib plots when saving a figure to disk with fig.savefig()
. None seem to show how to do this for displaying the figure with plt.show()
rather than saving it.
How do I remove the gray around the following figure (without saving it to disk)?
import matplotlib.pyplot as plt
fig, ax = plt.subplots(facecolor='gray')
ax.set_facecolor('pink')
ax.scatter([5, 1, 3], [1, 2, 3], s=100, c='b')
ax.axis('on')
ax.margins(0)
ax.set_aspect('equal')
ax.tick_params(which="both", direction="in")
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
fig.subplots_adjust(0, 0, 1, 1)
fig.tight_layout()
plt.show()
Above, the gray margin of the figure remains around the pink ax, no matter what I do. Below, I can remove it when saving to disk:
extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
fig.savefig('test.jpg', facecolor='gray', bbox_inches=extent)
This is the image I want to "show." But I can find nothing to re-create that bbox_inches=extent
functionality outside of the savefig
function. So how do I remove the gray around the plot and then show it with plt.show
?
Upvotes: 2
Views: 2157
Reputation: 39072
It is a simple solution using the argument frameon=False
while creating the axis instance as shown in this answer
fig, ax = plt.subplots(facecolor='gray', frameon=False)
which produces the following with plt.show()
.
EDIT: I also now remove the axes around the figure using the following
for spine in ['top', 'right', 'left', 'bottom']:
ax.spines[spine].set_visible(False)
or as a one-liner:
_ = [s.set_visible(False) for s in ax.spines.values()]
Upvotes: 3