在Bokeh中,我可以使用LabelSet
以编程方式为我的绘图中的每个点添加文本注释。下面我举一个简单的条形图的例子:
import numpy as np
import pandas as pd
# Make some data
dat = \
(pd.DataFrame({'team':['a','b','c'], 'n_people':[10,5,12]})
.assign(n_people_percent = lambda x: (x['n_people']/np.sum(x['n_people'])*100)
.round(1).astype('string') + '%')
)
dat
# Bar plot with text annotations for every bar
from bkcharts import show, Bar
from bkcharts.attributes import CatAttr
from bokeh.models import (ColumnDataSource, LabelSet)
source_labs = ColumnDataSource(data = dat)
p = Bar(data = dat, label = CatAttr(columns = 'team'), values = 'n_people')
labels = LabelSet(x = 'team', y = 'n_people',
text = 'n_people_percent', source = source_labs)
p.add_layout(labels)
show(p)
但是我不知道如何用Holoviews实现同样的目标。我可以很容易地制作相同的条形图而没有注释:
import holoviews as hv
hv.extension('bokeh')
p = hv.Bars(dat, kdims=['team'], vdims=['n_people'])
p
我可以添加一个文本标签,添加带有hv.Text
元素
p * hv.Text('a', 11, '37.0%')
但是我不知道如何在不为每个数据点(bar)单独显式调用hv.Text
的情况下标记每个条形图。问题似乎是hv.Text
不像其他元素那样接受data
参数,例如hv.Bars
,而只是x
和y
坐标。我的直觉是我应该能够做类似
p * hv.Text(dat, kdims=['team'], vdims=['n_people_percent'])
对此有任何帮助表示赞赏!
答案 0 :(得分:1)
像这样commit会向hv.Labels
添加矢量化标签,因此请尝试:
import holoviews as hv
hv.extension('bokeh')
p = hv.Bars(dat, kdims=['team'], vdims=['n_people'])
p * hv.Labels(dat, kdims=['team', 'n_people'], vdims=['n_people_percent'])