我正在使用Python进入Bokeh库,但我遇到了一些麻烦 . 我从Bokeh教程网站获得以下代码:
from bokeh.plotting import figure
from bokeh.io import output_notebook, show
output_notebook()
from bokeh.sampledata.autompg import autompg
from bokeh.models import HoverTool
from bokeh.plotting import ColumnDataSource
grouped = autompg.groupby("yr")
mpg2 = grouped["mpg"]
avg = mpg2.mean()
std = mpg2.std()
years = list(grouped.groups.keys())
american = autompg[autompg["origin"]==1]
japanese = autompg[autompg["origin"]==3]
p = figure(title="MPG by Year (Japan and US)")
p.vbar(x=years, bottom=avg-std, top=avg+std, width=0.8,
fill_alpha=0.2, line_color=None, legend="MPG 1 stddev")
p.circle(x=japanese["yr"], y=japanese["mpg"], size=10, alpha=0.5,
color="red", legend="Japanese")
p.triangle(x=american["yr"], y=american["mpg"], size=10, alpha=0.3,
color="blue", legend="American")
p.legend.location = "top_left"
show(p)
它有效,但我想添加一些功能,当你将鼠标悬停在一个点上时,它会显示马力 . 我尝试的是
grouped = autompg.groupby("yr")
mpg = grouped["mpg"]
avg = mpg.mean()
std = mpg.std()
years = list(grouped.groups.keys())
american = autompg[autompg["origin"]==1]
japanese = autompg[autompg["origin"]==3]
source = ColumnDataSource(data=
dict(autompg)
)
hover1 = HoverTool(tooltips=[("hp", "@hp")])
p = figure(title="MPG by Year (Japan and US)",tools=[hover1])
p.vbar(x=years, bottom=avg-std, top=avg+std, width=0.8,
fill_alpha=0.2, line_color=None, legend="MPG 1 stddev")
p.circle(x=japanese["yr"], y=japanese["mpg"], size=10, alpha=0.5,
color="red", legend="Japanese")
p.triangle(x=american["yr"], y=american["mpg"], size=10, alpha=0.3,
color="blue", legend="American")
p.legend.location = "top_left"
show(p)
所以定义一个HoverTool我希望能做到这一点 . 不幸的是,它只显示“hp:???”对于每个条目 . 我认为这是数据源的问题,但我在这里没有太多经验,也无法自己解决 . 我已经尝试了没有dict()的源代码,并且我试图将它设置为美国或日本,但这没有任何区别 .
谢谢!
1 回答
您需要将
source
传递给字形函数,并引用坐标的列名称 . 如果您将文字列表/数组(如上所述)传递给circle
等,那么Bokeh将在封面下为该数据创建一个CDS,但仅使用您传递给字形函数的数据(即没有额外的列)喜欢"hp") . 由于您尝试为数据的不同子集绘制不同的字形,最简单的方法是使用CDSView
在客户端上对它们进行分组 . 取而代之的是: