You need to enable JavaScript to run this app. 如何用mplcursors悬浮显示tkinter中堆叠柱状图各块的实际数值
优惠活动
大模型
产品
解决方案
定价
更多

如何用mplcursors悬浮显示tkinter中堆叠柱状图各块的实际数值

解决方案

你需要自定义mplcursors的注释回调函数,结合堆叠柱状图每个柱块的高度属性获取实际数值,替换默认的坐标显示。

核心实现步骤

  • 绘制堆叠柱状图时,可直接通过柱形对象bar的get_height()方法获取当前块的实际数值,若需要额外显示分类信息也可以在绘图时给bar对象绑定自定义属性
  • 给mplcursors绑定connect("add", 回调函数)事件,在回调中重写悬浮提示的文本

完整示例代码

import tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import mplcursors

# 初始化tkinter窗口
root = tk.Tk()
root.title("堆叠柱状图悬浮提示")

# 准备示例数据
categories = ["类别1", "类别2", "类别3", "类别4"]
series1 = [20, 35, 30, 27]
series2 = [25, 32, 34, 20]
series3 = [12, 18, 15, 17]
series_names = ["系列1", "系列2", "系列3"]
colors = ["#1f77b4", "#ff7f0e", "#2ca02c"]

# 创建matplotlib画布
fig = Figure(figsize=(6, 4), dpi=100)
ax = fig.add_subplot(111)

# 绘制堆叠柱状图,同时给每个bar绑定系列名称方便后续显示
bar1 = ax.bar(categories, series1, label=series_names[0], color=colors[0])
for b in bar1:
    b.series_name = series_names[0]
bar2 = ax.bar(categories, series2, bottom=series1, label=series_names[1], color=colors[1])
for b in bar2:
    b.series_name = series_names[1]
bar3 = ax.bar(categories, series3, bottom=[i+j for i,j in zip(series1, series2)], label=series_names[2], color=colors[2])
for b in bar3:
    b.series_name = series_names[2]

ax.legend()

# 嵌入tkinter
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw()
canvas.get_tk_widget().pack(fill=tk.BOTH, expand=1)

# 自定义悬浮提示回调
def show_actual_value(sel):
    # sel.artist就是当前悬浮的bar对象
    bar = sel.artist
    actual_value = bar.get_height()
    category = categories[int(bar.get_x() // bar.get_width())]
    # 自定义提示文本
    sel.annotation.set_text(f"分类:{category}\n{bar.series_name}:{actual_value}")
    # 可选:调整提示框样式
    sel.annotation.get_bbox_patch().set(fc="white", alpha=0.9)

# 初始化mplcursors并绑定回调
cursor = mplcursors.cursor([bar1, bar2, bar3], hover=True)
cursor.connect("add", show_actual_value)

root.mainloop()

关键说明

  • 回调函数中的sel.artist对应当前触发悬浮事件的图形元素,堆叠柱状图中就是你悬浮的那一小块柱形
  • 若不需要额外显示系列、分类信息,仅显示数值,直接取bar.get_height()作为提示文本即可
  • 初始化mplcursors.cursor时主动传入所有bar对象列表,可避免误触发其他图形元素的悬浮提示

内容的提问来源于stack exchange,提问作者Sriram

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 06:24:01