Skip to content

Instantly share code, notes, and snippets.

@thomasaarholt
Last active March 17, 2022 03:07
Show Gist options
  • Save thomasaarholt/3ac2d082dcc5d2a4a6e6c43fa3d80b26 to your computer and use it in GitHub Desktop.
Save thomasaarholt/3ac2d082dcc5d2a4a6e6c43fa3d80b26 to your computer and use it in GitHub Desktop.
Save matplotlib figures with no whitespace
import matplotlib.pyplot as plt
def save(filepath="image.png", fig=None):
'''Save the current image with no whitespace
Example filepath: "myfig.png" or r"C:\myfig.pdf"
Based on answers from https://stackoverflow.com/questions/11837979/
'''
import matplotlib.pyplot as plt
if not fig:
fig = plt.gcf()
plt.subplots_adjust(0,0,1,1,0,0)
for ax in fig.axes:
if ax.aname == 'colorbar':
continue
ax.axis('off')
ax.margins(0,0)
ax.xaxis.set_major_locator(plt.NullLocator())
ax.yaxis.set_major_locator(plt.NullLocator())
fig.savefig(filepath, pad_inches = 0, bbox_inches='tight')
@thomasaarholt
Copy link
Author

Latest revision handles both subplots with multiple axes as well as the normal plt.figure().

@thomasaarholt
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment