A bug in fig.write_image

I use python 3.11.9 and plotly 6.2.0 to build some scientific graphics and recently I stumbled upon a very nasty bug (supposedly) that took me an hour to figure out. It is related to the static import via fig.write_image. In the documentation it is said:

width (int or None) –

The width of the exported image in layout pixels. If the scale property is 1.0, this will also be the width of the exported image in physical pixels.

If not specified, will default to:

  • plotly.io.defaults.default_width if engine is β€œkaleido”

and the same for the β€œheight” parameter. However, it does not work as supposed. Here is an example:

  1. I create a figure with 1x5 ratio (for demonstration).
fig = go.Figure()
fig.update_layout(
                  height = 600,
                  width = 3000,
                  autosize = False, # Can be True, it does not matter
                  )
  1. I fill it with some traces

  2. If I render it in VS code or in browser, I get what I expect:

a very loooong image

  1. If, however, I try to save it using write_image without explicitly specifying width and height (because I expect it to be done automatically), I get image with different sizes:

fig.write_image(filename, scale = 1.) or fig.write_image(filename) give

if I use fig.write_image(filename, scale = 5.) it only increases DPI, but the width/height ratio are the same

  1. I spent a lot of time to figure out how to keep the same dimensionality when saving the image (I needed to increase the scale and as far as I know this can be done only using write_image). Turned out, I just needed to specify width and height explicitly:

fig.write_image(filename, width = fig.layout.width, height = fig.layout.height, scale = 5.) gives

So it seems like the documentation does not represent how in reality write_image works. This can be a problem for many people who want their images to be saved exactly as they want them to be.