python - Matplotlib - 堆叠条形图和工具提示
问题描述
当鼠标悬停在条形图上时,此代码返回工具提示。我想在堆积条形图的情况下修改代码,并在鼠标悬停在条形图的部分时获得该部分的特定工具提示。我不知道如何formatter
相应地修改。
这是我要实现的目标的说明。如果鼠标悬停在第三条的蓝色部分,工具提示将包含信息“ggg, hhh, iii”,如果鼠标悬停在第三条的绿色部分,工具提示将包含信息“555, 666”。
import numpy as np
import matplotlib.pyplot as plt
from mpldatacursor import datacursor
attendance = [['aaa', 'bbb', 'ccc'],
['ddd', 'eee', 'fff'],
['ggg', 'hhh', 'iii'],
['jjj', 'kkk', 'lll']]
attendance2 = [['111', '222'],
['333', '444'],
['555', '666'],
['777', '888']]
x = range(len(attendance))
y = [10, 20, 30, 40]
y2 = [5, 10, 15, 20]
fig, ax = plt.subplots()
ax.bar(x, y, align='center', bottom=0, color='lightblue')
ax.bar(x, y2, align='center', bottom=y, color='lightgreen')
ax.margins(0.05)
ax.set_ylim(bottom=0)
def formatter(**kwargs):
dist = abs(np.array(x) - kwargs['x'])
i = dist.argmin()
return '\n'.join(attendance[i])
datacursor(hover=True, formatter=formatter)
plt.show()
解决方案
格式化程序的包括矩形补丁的详细信息 - 具体来说,kwargs
, , ,等。在这种情况下,我们只需要知道矩形的底部在哪里 - 如果是,我们可以使用它来设置标签,否则我们想用。mpldatacursor
bottom
left
height
width
0
attendance
attendance2
因此,您可以将formatter
功能更改为:
def formatter(**kwargs):
dist = abs(np.array(x) - kwargs['x'])
i = dist.argmin()
labels = attendance if kwargs['bottom'] == 0 else attendance2
return '\n'.join(labels[i])
这给出了这个结果:
推荐阅读
- mongodb - php mongodb中的投影
- javascript - 如何使用迭代器嵌套循环?
- node.js - golang base64 编码与 nodejs 缓冲区 base64 编码
- php - PHP 分页集成脚本在输出中显示没有页面
- r - 逐行合并多个矩阵并将其存储在一个新矩阵中
- c# - 使用 jQuery.timepicker 仅在 ASP.NET MVC 中节省时间
- javascript - PHP从div中获取p元素
- javascript - 更改悬停时的图像会更改整行的图像
- node.js - 在最后一行之前添加值行并保留最后一行格式
- go - How to index entire GOPATH for existing project in Goland?