Issue
I'm trying to add some HTML to a Plotly figure I have built in Python, so that when I export both to HTML they both show up. I don't want this to be a title, but specifically an HTML string added to the Plotly figure.
An example is below, and works fine when I just run in a Jupyter Notebook, but the HTML string isn't actually a part of the Plotly figure, so when I export the figure to HTML it doesn't show up.
import plotly.express as px
from IPython.display import display, HTML
display(HTML('<h1>Hello, world!</h1>'))
data_canada = px.data.gapminder().query("country == 'Canada'")
fig = px.bar(data_canada, x='year', y='pop')
fig.show()
fig.write_html('fig.html')
Does anyone know how to achieve this?
Solution
This gets close but it isn't actually HTML being added while many, but not all common tags do work:
import plotly.express as px
from IPython.display import display, HTML
#display(HTML('<h1>Hello, world!</h1>'))
data_canada = px.data.gapminder().query("country == 'Canada'")
fig = px.bar(data_canada, x='year', y='pop', title = 'MOOT BUT ADDS SOME SPACING IN FIGURE LAYOUT')
fig.update_layout(title_text='Title placeholder', title_x=0.5) # based on fig.update_layout(title_text='Your title', title_x=0.5)
fig.add_annotation(text="<b>Hello, world!</b>",
xref="paper", yref="paper",
x=-0.03, y=1.0999, showarrow=False, font=dict(size=28)) # based on
# https://stackoverflow.com/a/76203314/8508004 https://community.plotly.com/t/how-to-add-a-text-area-with-custom-text-as-a-kind-of-legend-in-a-plotly-plot/24349/4 https://plotly.com/python/text-and-annotations/ https://plotly.com/python/figure-structure/#positioning-with-paper-container-coordinates-or-axis-domain-coordinates
fig.show()
fig.write_html('fig.html')
What gets added is a text annotation that works with <b>
or <br>
HTML tags, but not <h1>
.
I also added a title since you said you already are using that despite that not being in your MRE.
Most of references are in my comment to the OP and the rest needed to round out this work around are added as comments in the code here.
Note, you cannot go by what the Jupyter cell output will be to get placement of text right in resulting fig.html
. This inconveniently then takes some trial-and-error adjusting coordinates.
Result of fig.html
opened shows text present following export the figure to HTML:
Answered By - Wayne
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.