robintw robintw - 1 year ago 154
Python Question

Reduce left and right margins in matplotlib plot

I'm struggling to deal with my plot margins in matplotlib. I've used the code below to produce my chart:

c = plt.colorbar()
c.set_label("Number of Slabs")

However, I get an output figure with lots of white space on either side of the plot. I've searched google and read the matplotlib documentation, but I can't seem to find how to reduce this.

Answer Source

One way to automatically do this is the bbox_inches='tight' kwarg to plt.savefig.


import matplotlib.pyplot as plt
import numpy as np
data = np.arange(3000).reshape((100,30))
plt.savefig('test.png', bbox_inches='tight')

Another way is to use fig.tight_layout()

import matplotlib.pyplot as plt
import numpy as np

xs = np.linspace(0, 1, 20); ys = np.sin(xs)

fig = plt.figure()
axes = fig.add_subplot(1,1,1)
axes.plot(xs, ys)

# This should be called after all axes have been added