How can I change the python plotly figure id?

754 views Asked by At

Is there a way to change the id of a plotly figure in python?

For example if I run this code taken from the plotly webpage:

import plotly.graph_objects as go

fig = go.Figure()

config = dict({'scrollZoom': True})

fig.add_trace(
    go.Scatter(
        x=[1, 2, 3],
        y=[1, 3, 1]))

fig.show(config=config)

If I inspect the element I can see that the figure is in a div container with a strange id (cd3a3c26...) .screenshot of div-id

How can I change this to my-figure?

And is it possible to also change the div class?

Thank you for your help!

1

There are 1 answers

0
Filipe On

It's a bit of an old question, but starting on version 5.5.0 there is a way: plotly introduced div_id argument to the html generation, where you can select the id of the div container:

div_id (str (default None)) – If provided, this is the value of the id attribute of the div tag. If None, the id attribute is a UUID.

I don't think it's possible to change directly on fig.show() though. I also don't think it's possible to change the class directly. One possibility is to add "by hand" using text replacement and javascript:

import plotly.graph_objects as go

fig = go.Figure()

config = dict({'scrollZoom': True})

fig.add_trace(
    go.Scatter(
        x=[1, 2, 3],
        y=[1, 3, 1]))

html = fig.to_html(full_html=True, include_plotlyjs='cdn', config=config, div_id='test')

html = html.replace("</body>","<script> document.querySelectorAll('.plotly-graph-div').forEach(element => { element.classList.add('newClass') }); </script></body>")

with open("test.html", 'w') as f:
    f.write(html)

Results in: id="test" class="... newClas"