In a plotly dash app, I am adding a text annotation with a clickable link that has a hash in it.
topic = "Australia" # might contain spaces
hashtag = "#" + topic
annotation_text=f"<a href=\"https://twitter.com/search?q={urllib.parse.quote_plus(hashtag)}&src=typed_query&f=live\">{topic}</a>"
I need the output html to contain "https://twitter.com/search?q=%23Australia&src=typed_query&f=live"
but I can't get the "#" character to encode properly. It gets double encoded to %2523.
Minimal Working Example:
import dash
from dash.dependencies import Input, Output
import plotly.express as px
import urllib.parse
df = px.data.gapminder()
all_continents = df.continent.unique()
app = dash.Dash(__name__)
app.layout = dash.html.Div([
dash.dcc.Checklist(
id="checklist",
options=[{"label": x, "value": x}
for x in all_continents],
value=all_continents[4:],
labelStyle={'display': 'inline-block'}
),
dash.dcc.Graph(id="line-chart"),
])
@app.callback(
Output("line-chart", "figure"),
[Input("checklist", "value")])
def update_line_chart(continents):
mask = df.continent.isin(continents)
fig = px.line(df[mask],
x="year", y="lifeExp", color='country')
annotations = []
df_last_value = df[mask].sort_values(['country', 'year', ]).drop_duplicates('country', keep='last')
for topic, year, last_lifeExp_value in zip(df_last_value.country, df_last_value.year, df_last_value.lifeExp):
hashtag = "#" + topic
annotations.append(dict(xref='paper', x=0.95, y=last_lifeExp_value,
xanchor='left', yanchor='middle',
text=f"<a href=\"https://twitter.com/search?q={urllib.parse.quote_plus(hashtag)}&src=typed_query&f=live\">{topic}</a>",
# text=f"<a href=\"https://twitter.com/search?q=#{urllib.parse.quote_plus(topic)}&src=typed_query&f=live\">{topic}</a>",
font=dict(family='Arial',
size=16),
showarrow=False))
fig.update_layout(annotations=annotations)
return fig
app.run_server(debug=True)
When you run this and click on the text "Australia" at the end of the line graph, it should open up a twitter search page for #Australia.
What I've tried:
- just using a bare "#" character:
text=f"<a href=\"https://twitter.com/search?q=#{urllib.parse.quote_plus(topic)}&src=typed_query&f=live\">{topic}</a>"
Here, the # character is not encoded as %23 in the output, which results in a broken link for twitter.
https://twitter.com/search?q=#mytopic&src=typed_query&f=live
link
- using quote_plus on the hashtag
text=f"<a href=\"https://twitter.com/search?q=#{urllib.parse.quote_plus(hashtag)}&src=typed_query&f=live\">{topic}</a>"
Here, the %23 (the encoded # character) gets encoded again, resulting in %2523 in the output.
https://twitter.com/search?q=%2523mytopic&src=typed_query&f=live
link
How do I get it to correctly encode the # (to %23) so I get
href="https://twitter.com/search?q=%23mytopic&src=typed_query&f=live