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()
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Chloe
  • 127
  • 1
  • 12

1 Answers1

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

JohanC
  • 71,591
  • 8
  • 33
  • 66
  • I tried your code on Jupyter notebook but for some reason, it doesn't work. I don't get any errors too. – Chloe Feb 24 '21 at 16:42
  • You'll need `%matplotlib notebook` instead of `%matplotlib inline` to have interactivity. See e.g. [canvas.mpl_connect in jupyter notebook](https://stackoverflow.com/questions/43923313/canvas-mpl-connect-in-jupyter-notebook) or [Javascript Error: IPython is not defined in JupyterLab](https://stackoverflow.com/questions/51922480/javascript-error-ipython-is-not-defined-in-jupyterlab/56416229#56416229) – JohanC Feb 24 '21 at 17:15
  • 1
    `%matplotlib qt` works in `Jupyter Lab` for interactive plots – Trenton McKinney Aug 16 '21 at 16:54