robintw - 7 months ago 77

Python Question

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

`plt.imshow(g)`

c = plt.colorbar()

c.set_label("Number of Slabs")

plt.savefig("OutputToUse.png")

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

One way to automatically do this is the `bbox_inches='tight'`

kwarg to `plt.savefig`

.

E.g.

```
import matplotlib.pyplot as plt
import numpy as np
data = np.arange(3000).reshape((100,30))
plt.imshow(data)
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
fig.tight_layout()
fig.savefig('test.png')
```