How to add a link/hyperlink to seaborn SNS graph?

Viewed 163

I have outputted some data on my seaborn (SNS) graph successfully. I would like to add a link/hyperlink anywhere on the graph (preferably on the title) where the user can click and they will be redirected to a specific webpage. I have looked online how to do this but not sure if Seaborn offers this feature.

Snippet of my code:

dataframe = pd.read_csv('C:\filename.csv', delimiter=",", index_col=False)
dataframe.reset_index(drop=True, inplace=True)


dataframe.drop("Asset Group Title",axis=1,inplace=True)


sns.set(style="ticks")
sns.despine(left=True, bottom=True)

sns.barplot(data=dataframe).set(title="Soccer", ylabel="Quantity")
plt.xticks(rotation=30)

plt.tight_layout()

plt.show()

How my graph looks: - Would like a hyperlink where it says "Soccer Groups"

enter image description here

Any suggestions/advice is appreciated

1 Answers

Using webbrowser and a matplotlib pick event you can make elements in an interactive plot act like hyperlinks:

import webbrowser
import matplotlib.pyplot as plt
from matplotlib.text import Text
import numpy as np


def pick_url():
    fig, ax = plt.subplots(1, 1)
    ax.set_title("https://stackoverflow.com", picker=True)
    (line,) = ax.plot(np.random.rand(100), "o")

    def on_pick(event):
        if isinstance(event.artist, Text):
            text = event.artist
            print(f"Attempting to open {text.get_text()!r}")
            webbrowser.open(text.get_text())

    fig.canvas.mpl_connect("pick_event", on_pick)


if __name__ == "__main__":
    pick_url()
    plt.show()

This demo gets the URL straight from the plot title, but you can get/generate the URL that you want however you need.

Related