Explain Codes LogoExplain Codes Logo

Savefig outputs blank image

python
matplotlib
data-visualization
subplots
Nikita BarsukovbyNikita Barsukov·Aug 9, 2024
TLDR

If plt.savefig('output.png') results in a blank output, save the plot prior to executing plt.show(). Plot elements rendered post-display (plt.show()) are not stored, which leads to a blank image.

import matplotlib.pyplot as plt plt.plot([1, 2, 3], [4, 5, 6]) # Time to save (no Agent Smith this time) plt.savefig('output.png') plt.show()

Jumping between figures: plt.gcf() to the rescue

In scenarios that require dealing with multiple figures, plt.gcf() is your lifeline. It captures the existing figure and eliminates the potential confusion:

fig = plt.figure() plt.plot([1, 2, 3], [4, 5, 6]) # Save Luke Skywalker, I mean, the current figure fig.savefig('current_figure.png')

Subplots — more is merrier

Adjust subplot parameters with plt.subplot() to prevent your plots from feeling claustrophobic, because nobody likes cramped spaces, right?

fig, ax = plt.subplots(nrows=2, ncols=2) # Lo and behold! Plotting on the axes # ... # Saving Private subplots_Figure fig.savefig('subplots_figure.png')

Dots per inch: What's in a dpi?

Aesthetics matter; and so does a higher dpi (dots per inch). Increase the dpi to bedazzle your audience with high-quality images:

plt.plot([1, 2, 3], [4, 5, 6]) # Save a high-res map to Hogwarts plt.savefig('high_res_output.png', dpi=300)

Coloring outside the lines

Ensure all your visual doodads, like legends and axis labels, are included and visible before preserving them for posterity. Remember, it's not complete without some captions and legends:

plt.plot([1, 2, 3], [4, 5, 6]) plt.xlabel('Time Travel Axis') # Labeled, for time travellers plt.ylabel('Parallel Universes') # More labels, because why not? plt.legend(['Multiverse Theory'], facecolor='white') # Legen-wait for it-Dary Legend plt.savefig('complete_plot.png') # Congrats, Universe Explorer!

No imshow or sns discrimination

Functions like imshow have feelings too!

plt.imshow(image_data) plt.colorbar() # Sprinkle some colors, it's a rainbow plt.savefig('image_plot.png') # Voila, we just saved a galaxy

For Seaborn enthusiasts, consider using the ax argument:

import seaborn as sns fig, ax = plt.subplots() sns.barplot(x="soup", y="crackers", data=df, ax=ax) # Who ordered soup bars? plt.savefig('seaborn_plot.png') # Saved. No soup for you!

The hide and seek game with data

Before applauding yourself for a job well done, ensure your data isn't in stealth mode. Verify it's visible:

plt.plot(x, y) # Set the limits, because boundaries are important plt.xlim(0, 10) plt.ylim(0, 10) plt.savefig('data_visible_plot.png') # A visible save for the unseen data

Filenames are identifiers too

Prevent the possible overwriting of plots by celebrating uniqueness. Use Time Stamps, because they sure won't repeat:

from datetime import datetime current_time = datetime.now().strftime('%Y%m%d_%H%M%S') filename = f'plot_{current_time}.png' # Personalized timestamp - a time capsule! plt.savefig(filename)