ax.set_axis_off(),或等效的ax.axis('off') 关闭轴线和标签。要删除更多空格,您可以使用
fig.savefig('/tmp/tight.png', bbox_inches='tight', pad_inches=0.0)
或to remove all whitespace up to the axis' boundaries,使用
extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
fig.savefig('/tmp/extent.png', bbox_inches=extent)
这些命令同样适用于ax.imshow(data) 或ax.plot(data)。
例如,
import numpy as np
import matplotlib.pyplot as plt
data = np.arange(1,10).reshape((3, 3))
fig, ax = plt.subplots()
ax.plot(data)
ax.axis('off')
# https://stackoverflow.com/a/4328608/190597 (Joe Kington)
# Save just the portion _inside_ the axis's boundaries
extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
fig.savefig('/tmp/extent.png', bbox_inches=extent)
fig.savefig('/tmp/tight.png', bbox_inches='tight', pad_inches=0.0)
extent.png (504x392):
tight.png (521x414):