Matplotlib - 堆积条形图和工具提示 [英] Matplotlib - Stacked bar chart and tooltip
问题描述
当鼠标悬停在条形图上时,此
将 numpy 导入为 np导入matplotlib.pyplot作为plt从mpldatacursor导入datacursor出席 = [['aaa', 'bbb', 'ccc'],['ddd', 'eee', 'fff'],['ggg', 'hhh', 'iii'],['jjj', 'kkk', 'll']]出席人数2 = [['111','222'],['333','444'],['555','666'],['777','888']]x = 范围(len(出勤))y = [10, 20, 30, 40]y2 = [5、10、15、20]无花果,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 格式化程序(**kwargs):dist = abs(np.array(x) - kwargs['x'])i = dist.argmin()返回'\ n'.join(出席[i])datacursor(悬停= True,formatter = formatter)plt.show()
mpldatacursor
格式化程序的 kwargs
包括矩形补丁的详细信息 - 特别是 底部
、left
、height
、width
等,在这种情况下,我们只需要知道矩形的底部在哪里是-如果其 0
,则可以使用 attendance
设置标签,否则,我们要使用 attendance2
.
因此,您可以将 formatter
函数更改为:
def formatter(** kwargs):dist = abs(np.array(x)-kwargs ['x'])i = dist.argmin()标签 = 出勤,如果 kwargs['bottom'] == 0 否则出勤 2返回'\ n'.join(labels [i])
产生这个结果:
This code returns a tooltip when the mouse hovers over a bar chart. I would like to modify the code in the case of a stacked bar chart and get a specific tooltip of the section when the mouse hovers the section of the bar chart.
I can't figure out how to modify the formatter
accordingly.
Here an illustration of what I am trying to achieve. If the mouse hovers the blue section of the third bar, the tooltip will contain the information "ggg, hhh, iii" and if the mouse hovers the green section of the third bar, the tooltip will contain the information "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()
the kwargs
for the mpldatacursor
formatter include details of the rectangle patch - specifically, the bottom
, left
, height
, width
, etc. In this case, we just need to know where the bottom of the rectangle is - if its 0
, we can use attendance
to set the label, otherwise we want to use attendance2
.
So, you can change your formatter
function to:
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])
Which gives this result:
这篇关于Matplotlib - 堆积条形图和工具提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!