【问题标题】:Hovering through stacked bar chart using mplcursors使用 mplcursors 悬停在堆积条形图上
【发布时间】:2021-11-13 23:14:43
【问题描述】:

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

在这里,如果我尝试使用 mplcursors 将鼠标悬停在栏上。它显示 y 轴值,我需要显示条形的值

我用过

mplcursors.cursor(hover=True)

如何显示有效柱值?

【问题讨论】:

    标签: python matplotlib mplcursors


    【解决方案1】:

    您可以制作自定义函数来更新注释。这是一个例子:

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

    【讨论】:

    • 如果这回答了您的问题,您可能会将marking 的答案视为已接受。
    猜你喜欢
    • 2021-05-24
    • 2018-12-26
    • 2017-02-26
    • 2017-11-02
    • 2017-08-22
    • 2014-02-09
    相关资源
    最近更新 更多