Plt.show shows full graph but savefig is cropping the image

PythonMatplotlib

Python Problem Overview


My code is succesfully saving images to file, but it is cropping important details from the right hand side. Answers exist for fixing this problem when it arises for plt.show, but it is the savefig command that is incorrectly producing the graph in this example. How can this be fixed?

The relevant sample of my code:

import glob
import os
for file in glob.glob("*.oax"):
    try:
        spc_file = open(file, 'r').read()
        newName = file[6:8] + '-' + file[4:6] + '-' + file[0:4] + ' ' + file[8:12] +  ' UTC (Observed) - No Sea Breeze Day'
        plt.title(newName, fontsize=12, loc='left')
        plt.savefig('X:/' + newName + '.png')        
        plt.show()
    except Exception:
        pass

And the images (top is plt.show and bottom is file produced from savefig:

Image when shown with plt.show Image when saved to file


Python Solutions


Solution 1 - Python

You may try

plt.savefig('X:/' + newName + '.png', bbox_inches='tight')

Or you may define figure size like

fig = plt.figure(figsize=(9, 11))
...
plt.savefig(filename, bbox_inches = 'tight')

Solution 2 - Python

As described in the documentation you may also try:

plt.tight_layout()

Solution 3 - Python

Another very easy solution is saving a plot to a .pdf format. This have worked for me many times when bbox_inches = 'tight'and plt.tight_layout() didn't help.

Syntax is just:

plt.savefig('X:/' + newName + '.pdf')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoss KirkView Question on Stackoverflow
Solution 1 - PythonSerenityView Answer on Stackoverflow
Solution 2 - Pythonsaty035View Answer on Stackoverflow
Solution 3 - PythonMDDawid1View Answer on Stackoverflow