Matplotlib - 堆积条形图和工具提示
Matplotlib - Stacked bar chart and tooltip
这 code returns 当鼠标悬停在条形图上时的工具提示。我想在堆叠条形图的情况下修改代码,并在鼠标悬停在条形图的部分时获得该部分的特定工具提示。
我不知道如何相应地修改 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()
mpldatacursor
格式化程序的 kwargs
包含矩形补丁的详细信息 - 具体来说,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])
结果如下:
这 code returns 当鼠标悬停在条形图上时的工具提示。我想在堆叠条形图的情况下修改代码,并在鼠标悬停在条形图的部分时获得该部分的特定工具提示。
我不知道如何相应地修改 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()
mpldatacursor
格式化程序的 kwargs
包含矩形补丁的详细信息 - 具体来说,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])
结果如下: