Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get width and height of plotly figure

Tags:

python

plotly

e.g. if I write

import plotly.express as px

df = px.data.tips()
fig = px.scatter(df, x="total_bill", y="tip", facet_col="sex")

then how can I get the width and height of fig?

If I do

fig.layout.width

then I get None.

like image 397
ignoring_gravity Avatar asked Oct 16 '25 11:10

ignoring_gravity


1 Answers

That is the correct way to get the width.

fig.layout.width is None because the width has not been set yet.

If you set it explicitly you can retrieve it

fig = px.scatter(df, x="total_bill", y="tip", facet_col="sex", width=200)
>>> fig.layout.width
200

If not set explicitly the width is initialised when executing the show method based on defaults defined by plotly.js.

show(*args, **kwargs) Show a figure using either the default renderer(s) or the renderer(s) specified by the renderer argument

Parameters
...
width (int or float) – An integer or float that determines the number of pixels wide the plot is. The default is set in plotly.js.
...

If we look at the plotly.js documentation we see the default width is 700 and the default height is 450.

If you set fig.layout.autosize = False you can see that these defaults are correct. Otherwise the width and height are re-initialised on each relayout.

autosize: Determines whether or not a layout width or height that has been left undefined by the user is initialized on each relayout. Note that, regardless of this attribute, an undefined layout width or height is always initialized on the first call to plot.

https://plotly.com/javascript/reference/layout/#layout-autosize

like image 184
Bas van der Linden Avatar answered Oct 18 '25 06:10

Bas van der Linden



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!