0

How can I modify this plot to show me the value of each bar upon hovering mouse?

sns.barplot(x = "date", y = "no_of_dogs", data = dogs_adopted_per_day, palette="husl")
plt.show()

1 Answer 1

2

You could employ mplcursors as follows:

import matplotlib.pyplot as plt
import mplcursors
import numpy as np
import pandas as pd
import seaborn as sns

df = pd.DataFrame({"date": pd.date_range('20210101', periods=10),
                   "no_of_dogs": np.random.randint(10, 30, 10)})
fig, ax = plt.subplots(figsize=(15, 5))
sns.barplot(x="date", y="no_of_dogs", data=df, palette="husl", ax=ax)

x_dates = df['date'].dt.strftime('%Y-%m-%d')
ax.set_xticklabels(labels=x_dates)

cursor = mplcursors.cursor(hover=True)
@cursor.connect("add")
def on_add(sel):
    x, y, width, height = sel.artist[sel.target.index].get_bbox().bounds
    sel.annotation.set(text=f"{x_dates[round(x)]}\n{height:.0f}",
                       position=(0, 20), anncoords="offset points")
    sel.annotation.xy = (x + width / 2, y + height)

plt.show()

example plot

Sign up to request clarification or add additional context in comments.

3 Comments

I tried your code on Jupyter notebook but for some reason, it doesn't work. I don't get any errors too.
You'll need %matplotlib notebook instead of %matplotlib inline to have interactivity. See e.g. canvas.mpl_connect in jupyter notebook or Javascript Error: IPython is not defined in JupyterLab
%matplotlib qt works in Jupyter Lab for interactive plots

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.