Question

I have some plots and I want so save them as .eps. But the output from PyCharm in Spyder differs from the output which savefig generates.

Here is the complete code: (based on this discussion: Matplotlib - Broken axis example: uneven subplot size)

# -*- coding: utf-8 -*-
import matplotlib.pylab as plt
import matplotlib.gridspec as gridspec
import numpy as np


dipole=[5.65,5.97,6.13,6.13,6.13]
cellsize1=np.array([40000./256,40000./512,40000./1024,40000./4096,40000./8192])
exchange=[22.3,20.6,20.4]
cellsize2=np.array([40000./1024,40000./4096,40000./8192])

k_dipol=5.3
k_ex=22.

yerr1=np.multiply(cellsize1,k_dipol**2/(1000*2*np.pi))
yerr2=np.multiply(cellsize2,k_ex**2/(1000*2*np.pi))


fig=plt.figure(num=None, figsize=(10, 4), dpi=80, facecolor='w', edgecolor='k')
font = {'weight' : 'normal', 'size'   : 13}
plt.rc('font', **font)

ylim2  = [4.5, 6.5]
ylim = [19., 25.5]
ylimratio = (ylim[1]-ylim[0])/(ylim2[1]-ylim2[0]+ylim[1]-ylim[0])
ylim2ratio = (ylim2[1]-ylim2[0])/(ylim2[1]-ylim2[0]+ylim[1]-ylim[0])
gs = gridspec.GridSpec(2, 1, height_ratios=[ylimratio, ylim2ratio])

ax = fig.add_subplot(gs[0])
plot1=ax.errorbar(cellsize2,exchange, yerr=yerr2, fmt='--o', label='Austausch')
ax.set_ylim(ylim)
ax.grid(True)
ax.xaxis.tick_top()
ax.tick_params(labeltop='off')

ax2 = fig.add_subplot(gs[1])
plot2=ax2.errorbar(cellsize1,dipole, yerr=yerr1, fmt='g--o', label='Dipol')
ax2.set_ylim(ylim2)
ax2.yaxis.set_ticks([5,6])
ax2.set_yticklabels([5,6])
ax2.grid(True)
ax2.xaxis.tick_bottom()
ax2.set_xlabel(u'Auflösung (nm/Zelle)')
ax2.set_ylabel(u'Wellenvektor (1/µm)')
ax2.yaxis.set_label_coords(0.05, 0.5, transform=fig.transFigure)

xlim = ax2.get_xlim()
ax.set_xlim(xlim)
ax2.set_xlim(xlim)

plt.subplots_adjust(hspace=0.1)
fig.legend((plot1, plot2), ('Austauschwelle','Dipolwelle'),
       bbox_to_anchor=[0.85, 0.9], prop={'size':9})

plt.savefig('Aufloesungsvergleich_k_vektoren.eps', bbox_inches='tight', pad_inches=0.05)
plt.show()

This code gernerates the following outputs

enter image description here

The upper part is the eps-file. The lower part is the window which pops up when I run the code. Please have a look at the location of the legend...

I guess this is not normal?

Was it helpful?

Solution

When you choose bbox_inches='tight' when saving a matplotlib figure as an image using savefig the function will attempt to find the smallest, tighest box it can that encloses all of your objects.

One unfortunate side-effect of this is that it can seemingly "move" objects when you compare the output from plt.show() and the output from plt.savefig(). If you remove bbox_inches='tight' then this should solve your problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top