我在 tkinter 选项卡中有一个堆积条形图。
在这里,如果我尝试使用 mplcursors 将鼠标悬停在栏上。它显示 y 轴值,我需要显示条形的值
我用了
mplcursors.cursor(hover=True)
我怎样才能显示有效的条形值?
我在 tkinter 选项卡中有一个堆积条形图。
在这里,如果我尝试使用 mplcursors 将鼠标悬停在栏上。它显示 y 轴值,我需要显示条形的值
我用了
mplcursors.cursor(hover=True)
我怎样才能显示有效的条形值?
您可以制作自定义函数来更新注释。这是一个例子:
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()