python-3.xmatplotlibseabornbar-chartmplcursors

How to add a hovering annotation on a bar plot with mplcursors


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()

Solution

  • 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