在Holoviews图中为每个数据点添加文本注释

时间:2017-09-14 15:26:30

标签: python bokeh holoviews

在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

enter image description here

# 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)

enter image description here

但是我不知道如何用Holoviews实现同样的目标。我可以很容易地制作相同的条形图而没有注释:

import holoviews as hv
hv.extension('bokeh')

p = hv.Bars(dat, kdims=['team'], vdims=['n_people'])
p

enter image description here

我可以添加一个文本标签,添加带有hv.Text元素

的叠加层
p * hv.Text('a', 11, '37.0%')

enter image description here

但是我不知道如何在不为每个数据点(bar)单独显式调用hv.Text的情况下标记每个条形图。问题似乎是hv.Text不像其他元素那样接受data参数,例如hv.Bars,而只是xy坐标。我的直觉是我应该能够做类似

的事情
p * hv.Text(dat, kdims=['team'], vdims=['n_people_percent'])

对此有任何帮助表示赞赏!

1 个答案:

答案 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'])