为了账号安全,请及时绑定邮箱和手机立即绑定

如何设置条形图悬停以显示 x 轴的标签?

如何设置条形图悬停以显示 x 轴的标签?

慕码人2483693 2021-12-17 16:05:22
我已经生成了一个简单的条形图。为了使其更具交互性,我在图表中添加了 Hovertool。from bokeh.io import show, output_notebookfrom bokeh.plotting import figure, output_filefrom bokeh.models.glyphs import HBarfrom bokeh.models import ColumnDataSource, Legend, HoverTooloutput_notebook()# Set x and yfunctions = ['func_1', 'func_2', 'func_3']percentage = [233.14, 312.03, 234.00]# Set data source (color needs to be set precisely with len(category))source = ColumnDataSource(data=dict(functions=functions, percentage=percentage))# Set the x_range to the list of categories abovep = figure(x_range=functions, plot_height=600, plot_width=800, title="The Overall Use of my functions",          x_axis_label='Functions', y_axis_label='Percentage')# Categorical values can also be used as coordinatesp.vbar(x='functions', top='percentage', width=0.9, source=source)p.add_tools(HoverTool(tooltips=[('Percentage', "@percentage")]))show(p)虽然它正确显示了 y 轴的值,但我想显示 x 轴的标签(例如,Func1:9.45)。就像链接中显示的图片一样(我还不能发布图片):更新#1 我试图想出一些东西,这就是我得到的:# Set Hoverpercentage = list(map(lambda i: str(i), percentage))my_hover = list(zip(functions, percentage))p.add_tools(HoverTool(tooltips=my_hover))事实证明它显示了每个条中的每个细节,如下所示
查看完整描述

1 回答

?
HUWWW

TA贡献1874条经验 获得超12个赞

此代码适用于 Bokeh v1.0.4。


import math

import numpy as np

import pandas as pd

from bokeh.models import ColumnDataSource, HoverTool

from bokeh.plotting import figure, show

from bokeh.palettes import Category10


df = pd.DataFrame(data = np.random.rand(10, 1), columns = ['percentage'], index = ['Func {}'.format(nmb) for nmb in range(10)])

df['color'] = Category10[10]


source = ColumnDataSource(data = dict(functions = df.index.values, percentage = df['percentage'].values, color = df['color'].values))


p = figure(x_range = df.index.values, plot_height = 600, plot_width = 800, title = "The Overall Use of my functions",

           x_axis_label = 'functions', y_axis_label = 'percentage')


p.vbar(x = 'functions', top = 'percentage', width = 0.9, color = 'color', source = source)

p.add_tools(HoverTool(tooltips = '<font color=blue>@functions:</font><font color=red> @percentage</font>'))


p.xgrid.grid_line_color = None

p.xaxis.major_label_orientation = math.pi / 4  # Rotate axis' labels


show(p)

结果:

//img1.sycdn.imooc.com//61bc44f7000101a808240600.jpg

查看完整回答
反对 回复 2021-12-17
  • 1 回答
  • 0 关注
  • 164 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信