如何使用 mplcursors 在条形图上添加悬停注释

Posted

技术标签:

【中文标题】如何使用 mplcursors 在条形图上添加悬停注释【英文标题】:How to add a hovering annotation on a bar plot with mplcursors 【发布时间】:2022-01-23 04:52:29 【问题描述】:

如何修改此图以在鼠标悬停时显示每个条的值?

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

【问题讨论】:

【参考方案1】:

您可以使用mplcursors 如下:

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)]\nheight:.0f",
                       position=(0, 20), anncoords="offset points")
    sel.annotation.xy = (x + width / 2, y + height)

plt.show()

【讨论】:

我在 Jupyter notebook 上试过你的代码,但由于某种原因,它不起作用。我也没有收到任何错误。 您需要%matplotlib notebook 而不是%matplotlib inline 才能进行交互。参见例如canvas.mpl_connect in jupyter notebook 或 javascript Error: IPython is not defined in JupyterLab %matplotlib qtJupyter Lab 中工作,用于交互式绘图

以上是关于如何使用 mplcursors 在条形图上添加悬停注释的主要内容,如果未能解决你的问题,请参考以下文章

在悬停时在堆积条形图上绘制水平线(图表 js)

在这种情况下,如何使用 barh() 在条形图上显示值? [复制]

如何在列的分组条形图上添加误差线

如何在 matplotlib 中添加悬停注释

python使用matplotlib绘制水平条形图并在条形图上添加实际数值标签实战

使用 matplotlib 在条形图上添加值标签