Bokeh Hovertool堆叠条形图

2024-06-16 10:37:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我用下面的代码构建了一个博克堆积条形图。图表显示了哥本哈根地区的不同树木类型。目前,我有一个hoverTool,它显示树类型的树的数量(与树名对应的列),但我也希望它显示百分比(末尾带有_p的列),但是如何使用堆叠条形图来实现这一点

数据帧的缩减部分:

temp=pd.DataFrame( {'bydelsnavn': {0: 'Amager Vest', 1: 'Amager Øst', 2: 'Bispebjerg', 3: 'Brønshøj-Husum', 4: 'Indre By', 5: 'Nørrebro', 6: 'Valby', 7: 'Vanløse', 8: 'Vesterbro', 9: 'Østerbro'}, 'Alder': {0: 53.0, 1: 21.0, 2: 1.0, 3: 9.0, 4: 4.0, 5: 2.0, 6: 3.0, 7: 44.0, 8: 46.0, 9: 59.0}, 'Alderm': {0: 63.0, 1: 32.0, 2: 49.0, 3: 13.0, 4: 45.0, 5: 55.0, 6: 104.0, 7: 0.0, 8: 50.0, 9: 4.0}, 'Apple': {0: 94.0, 1: 109.0, 2: 115.0, 3: 12.0, 4: 22.0, 5: 81.0, 6: 41.0, 7: 3.0, 8: 132.0, 9: 51.0}, 'Alder_p': {0: 21.9, 1: 8.68, 2: 0.41, 3: 3.72, 4: 1.65, 5: 0.83, 6: 1.24, 7: 18.18, 8: 19.01, 9: 24.38}, 'Alderm_p': {0: 15.18, 1: 7.71, 2: 11.81, 3: 3.13, 4: 10.84, 5: 13.25, 6: 25.06, 7: 0.0, 8: 12.05, 9: 0.96}, 'Apple_p': {0: 14.24, 1: 16.52, 2: 17.42, 3: 1.82, 4: 3.33, 5: 12.27, 6: 6.21, 7: 0.45, 8: 20.0, 9: 7.73}})

我的代码:

treeName = ['Alder','Alderm','Apple']
treeName_p = ['Alder_p','Alderm_p','Apple_p']

colornames = named.__all__
colornames = colornames[:len(treeName)]

# Create an empty figure
p = figure(x_range = temp['bydelsnavn'].values,plot_width = 700, plot_height=400, 
           title='Tree pr. district', toolbar_sticky = False,
           tools = 'pan,wheel_zoom,reset')

# Stacked bar chart
renderers = p.vbar_stack(stackers=treeName,x='bydelsnavn',source=temp,
            width=0.8, color = colornames)

# Add the hover tool
for r in renderers:
    tree = r.name
    hover = HoverTool(tooltips=[
        ("%s" % tree, "@{%s}" % tree)
    ], renderers = [r])
    p.add_tools(hover)

# remove the grid
p.xgrid.grid_line_color=None
p.ygrid.grid_line_color=None
# Make sure bars stat at 0
p.y_range.start = 0
# remove - y-axis
p.yaxis.visible = False
# Remove the grey box around the plot
p.outline_line_color = None
# Turn the x-labels
p.xaxis.major_label_orientation = 0.5
# Remove tool bar logo
p.toolbar.logo = None
# Move the border of the left side to show "Amager"
p.min_border_left = 30

show(p)

我当前的图表如下所示: enter image description here


Tags: thenonetreeappleplottempcolorrenderers
1条回答
网友
1楼 · 发布于 2024-06-16 10:37:32

假设_p列的值实际上在数据源中,您只需将另一个工具提示添加到HoverTool

for r in renderers:
    tree = r.name
    p.add_tools(HoverTool(tooltips=[(tree, "@$name"),
                                    (f"{tree} %", f"@{tree}_p")],
                          renderers=[r]))

请注意@$name在那里是如何使用的——在这种特殊情况下没有必要这样做,但有时会派上用场

相关问题 更多 >