首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用mplcursor在堆叠条形图中悬停

使用mplcursor在堆叠条形图中悬停
EN

Stack Overflow用户
提问于 2021-09-20 08:18:03
回答 1查看 65关注 0票数 0

我在tkinter选项卡中有一个堆叠的条形图。

在这里,如果我尝试使用mplcursor在条中悬停。它在我需要显示条形图的值的地方显示y轴值

我用过

代码语言:javascript
复制
mplcursors.cursor(hover=True)

如何显示有效的条形值?

EN

回答 1

Stack Overflow用户

发布于 2021-09-24 15:07:49

您可以创建自定义函数来更新注释。下面是一个示例:

代码语言:javascript
复制
from matplotlib.container import BarContainer
import matplotlib.pyplot as plt
import mplcursors
import pandas as pd
import numpy as np


def show_annotation(sel):
    if type(sel.artist) == BarContainer:
        bar = sel.artist[sel.target.index]
        sel.annotation.set_text(f'{sel.artist.get_label()}: {bar.get_height():.1f}')
        sel.annotation.xy = (bar.get_x() + bar.get_width() / 2, bar.get_y() + bar.get_height() / 2)
        sel.annotation.get_bbox_patch().set_alpha(0.8)


df2 = pd.DataFrame({'alpha': [10, 20], 'beta': [np.nan, 30], 'gamma': [54, 38], 'delta': [42, 75]},
                   index=['First', 'Second'])

ax = df2.plot(kind='bar', stacked=True, rot=0, figsize=(15, 5), cmap='inferno')

cursor = mplcursors.cursor(hover=True)
cursor.connect('add', show_annotation)
plt.show()

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69251152

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档