'Save plot from matplotlib so that plot is centered

I am trying to make a plot in Python using matplotlib. Specifically, I am using contourf(Xm,Ym,Zm) with colorbar and saving the plot using figX.savefig('name'), with Xm,Ym,Zm being some meshgrids.

With the colorbar next to the actual plot, the plot is off-center using default parameters in savefig.

How can I produce a figure so that the resulting image file is centered on the center of the actual plot. Best case scenario; the size adjusts so that colorbars and such wont be cut off.

I cant seem to find anything I can use in the parameters of savefig(), and simply have no idea how to go about this.

Some code:

import matplotlib.pyplot as plt
import numpy as np

# make data
Xm, Ym = np.meshgrid(np.linspace(-3, 3, 256), np.linspace(-3, 3, 256))
Zm = (1 - Xm/2 + Xm**5 + Ym**3) * np.exp(-Xm**2 - Ym**2)
levels = np.linspace(Zm.min(), Zm.max(), 7)

# plot
fig, ax = plt.subplots()

cp = ax.contourf(Xm, Ym, Zm, levels=levels)

cbar = fig.colorbar(cp)

#plt.show()

fig.savefig('plots/contour-plot.png')

The red cross should be equal to the purple cross: enter image description here



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source