简体   繁体   中英

How can I change the python plotly figure id?

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... ) . 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!

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM