Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize a figure automatically in matplotlib

Is there a way to automatically resize a figure to properly fit contained plots in a matplotlib/pylab image?

I'm creating heatmap (sub)plots that differ in aspect ratio according to the data used.

I realise I could calculate the aspect ratio and manually set it, but surely there's an easier way?

like image 783
pufferfish Avatar asked Aug 13 '09 09:08

pufferfish


People also ask

How does Figsize work in Matplotlib?

figsize() takes two parameters- width and height (in inches). By default the values for width and height are 6.4 and 4.8 respectively. Where, x and y are width and height respectively in inches.


2 Answers

Use bbox_inches='tight'

import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm  X = 10*np.random.rand(5,3)  fig = plt.figure(figsize=(15,5),facecolor='w')  ax = fig.add_subplot(111) ax.imshow(X, cmap=cm.jet)  plt.savefig("image.png",bbox_inches='tight',dpi=100) 

...only works when saving images though, not showing them.

like image 200
pufferfish Avatar answered Sep 21 '22 15:09

pufferfish


Another way of doing this is using the matplotlib tight_layout function

import matplotlib.pyplot as plt fig,(ax) = plt.subplots(figsize=(8,4), ncols=1) data = [0,1,2,3,4] ax.plot(data) fig.tight_layout() fig.show() 
like image 38
Simon Hobbs Avatar answered Sep 17 '22 15:09

Simon Hobbs