77

For a project, I need to know the current size (in pixels) of my matplotlib figure, but I can't find how to do this. Does anyone know how to do this ?

VishnuVS
  • 1,055
  • 2
  • 14
  • 29
Tristan
  • 793
  • 1
  • 5
  • 5

3 Answers3

98
import matplotlib.plt
fig = plt.figure()
size = fig.get_size_inches()*fig.dpi # size in pixels

To do it for the current figure,

fig = plt.gcf()
size = fig.get_size_inches()*fig.dpi # size in pixels

You can get the same info by doing:

bbox = fig.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
width, height = bbox.width*fig.dpi, bbox.height*fig.dpi
Julien Spronck
  • 15,069
  • 4
  • 47
  • 55
  • Thank you, it gives me the size of the figure when first plotted I think, but it does not actualize if I change the size of my window and re draw my figure :/ – Tristan Apr 17 '15 at 15:02
  • it does for me. I first turned interactive plotting on `plt.ion()`. I created a figure `fig`. `size = fig.get_size_inches()*fig.dpi` returned `array([ 640., 480.])`. I resized it and recalculated the size and got `array([ 704., 270.])` – Julien Spronck Apr 17 '15 at 15:07
  • Thanks, I will investigate this way so. I just need to turn interactive plotting on now in my FigureCanvas :) – Tristan Apr 17 '15 at 15:31
  • is `fig.get_size_inches()*fig.dpi` width or height? – Joseph Garvin Nov 15 '19 at 19:26
  • @JosephGarvin both: `fig_width, fig_height = plt.gcf().get_size_inches()` – eric Jan 28 '21 at 15:34
12

Maybe this animation might help: enter image description here

enter image description here

Kolibril
  • 1,096
  • 15
  • 19
  • 1
    It should only illustrate the connection between dpi and figure_size, as an addition to the already good answer from Julien Spronck, however, If you don't find this useful, I can also remove this answer again. – Kolibril Nov 09 '20 at 18:12
  • 17
    I think it would be useful and pretty cool if you put code. – eric Nov 09 '20 at 18:33
  • here is the code: https://manimplotlib.readthedocs.io/en/latest/manimplotlib4.html – Kolibril Mar 21 '23 at 20:26
8

Quickly extract figure size in inches

To get width and height in inches I just use:

fig_width, fig_height = plt.gcf().get_size_inches()
print(fig_width, fig_height)

I put this here because this question is the first result that pops up when you search 'get matplotlib figure size', and the api most naturally works in inches, not pixels.

eric
  • 7,142
  • 12
  • 72
  • 138