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?


