169

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


Serenity
  • 35,289
  • 20
  • 120
  • 115
Joss Kirk
  • 1,873
  • 3
  • 11
  • 15
  • Can you make a simple example that others can test, preferably without having to download extra data and packages? – Neapolitan May 25 '16 at 04:57
  • 2
    @Neapolitan. That's a bit beyond my skill set. The answer provided below suggests that there is a generic solution for this problem, independent of the data. – Joss Kirk May 25 '16 at 05:29
  • @Neopolitan I don't know how the problem has arisen, so I'm not sure how to produce simpler data that could replicate it. – Joss Kirk May 25 '16 at 05:40

3 Answers3

309

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')
Serenity
  • 35,289
  • 20
  • 120
  • 115
  • 13
    This has to be the default option, bbox_inches='tight'. I used it in conjunction with a high dpi value and it worked wonderfully well. – Deepak V Feb 08 '19 at 05:46
  • Using plt.gcf().set_size_inches(width,height) and then plt.savefig(filename, bbox_inches = 'tight') works even better for nerdy-detailed-obsessive-compulsive-disorder customization – Rolando Gonzales Jan 20 '23 at 14:09
11

As described in the documentation you may also try:

plt.tight_layout()
Jurgen Strydom
  • 3,540
  • 1
  • 23
  • 30
saty035
  • 142
  • 2
  • 7
  • 1
    It works for me, but it changes the ratio width/height. Any idea how to also preserve the ratio? – Profiterole Jun 29 '21 at 17:51
  • Yes, you can set the ratios accordingly by using "plt.figure(figsize=(9, 3))" ;) – saty035 Jul 20 '21 at 16:12
  • I like this better than the accepted answer: it is easier to remember, and can be autocompleted to reduce human error. – Rafs Aug 23 '23 at 12:05
0

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')
MDDawid1
  • 92
  • 11