Last active
March 17, 2022 03:07
-
-
Save thomasaarholt/3ac2d082dcc5d2a4a6e6c43fa3d80b26 to your computer and use it in GitHub Desktop.
Save matplotlib figures with no whitespace
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Latest revision handles both
subplots
with multiple axes as well as the normalplt.figure()
.