Search code examples
pythonjupyter-notebookplotlyplotly-python

How can I set the width and height in a plotly theme?


Context

I use the .plot method of pandas dataframes throughout a JupyterLab notebook and have set the plotting backend to plotly and the default plotly theme to plotly

Every time I plot I do a .update_layout afterwards to set the width, height and margins. I do that because I plan on exporting the notebook to reveal.js slides, not setting those properties results in unpredictable output.

This is my example code, which creates a 200x200 plot without any margins.

import pandas as pd
import plotly.io as pio

pd.
options.plotting.backend = "plotly"
pio.templates.default = "plotly"

x = [1, 2, 3, 4]
y = [2, 4, 6, 8]
df = pd.DataFrame({"x": x, "y": y})

fig = df.plot(x=x, y=y)
fig.update_layout(width=200, height=200, margin=dict(l=0, r=0, t=0, b=0))
fig.show()

As I want this plot size and margins in all my plots, I wanted to make a theme which I can set at the beginning, such that I don't have to call .udpate_layout on every figure.

What I've tried

I tried this:

import pandas as pd
import plotly.io as pio

# Creat a custom theme and set it as default
pio.templates["custom"] = pio.templates["plotly"]
pio.templates["custom"].layout.margin = dict(l=0, r=0, t=0, b=0)
pio.templates["custom"].layout.width = 200
pio.templates["custom"].layout.height = 200
pio.templates.default = "custom"
x = [1, 2, 3, 4]
y = [2, 4, 6, 8]
df = pd.DataFrame({"x": x, "y": y})

fig = df.plot(x=x, y=y)
fig.show()

The resulting plot doesn't adhere to the size specifications unfortunately. The margin setting is respected though.

Question

How can I create a plotly theme to create plots of a specified size?


Solution

  • Turns out I was missing the autosize property in my template.

    When I set it to False:

    pio.templates["custom"].layout.autosize = False
    

    a 200x200 plot comes out.