How do you add a clickable link to each bar graph using Plotly Express in Python?

Viewed 709

So basically, I want a user to be directed to a specific website when they click a bar in a bar graph but I cant figure out how to do it. Couldn't find any resources for this either..

1 Answers

You can use HTML in annotations

import pandas as pd
import plotly.express as px

df = pd.DataFrame({"tag": ["pandas", "plotly", "matplotlib"]}).assign(
    val=1,
    url=lambda d: d["tag"].apply(
        lambda t: f"https://stackoverflow.com/questions/tagged/{t}?sort=Newest&filters=NoAnswers,NoAcceptedAnswer&edited=true"
    ),
)

fig = px.bar(df, y="val", x="tag")

for r in df.iterrows():
    fig.add_annotation(
        {
            "x": r[1]["tag"],
            "y": r[1]["val"],
            "text": f"""<a href="{r[1]["url"]}" target="_blank">{r[1]["tag"]}</a>""",
        }
    )

fig

enter image description here

Related