问题描述
在Bokeh中,我可以使用LabelSet
以编程方式向绘图中的每个点添加文本注释.下面,我给出一个简单条形图的示例:
In Bokeh I am able to add a text annotation to each point in my plot programmatically by using LabelSet
. Below I give an example for a simple bar plot:
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实现相同的功能.我可以很容易地在没有注释的情况下绘制相同的条形图:
However I am not sure how to achieve the same thing with Holoviews. I can make the same bar plot without the annotations very easily:
import holoviews as hv
hv.extension('bokeh')
p = hv.Bars(dat, kdims=['team'], vdims=['n_people'])
p
我可以添加一个带有hv.Text
元素的叠加层的文本标签
I can add a single text label adding an Overlay with the hv.Text
element
p * hv.Text('a', 11, '37.0%')
但是我不知道如何在不为每个数据点(条)分别显式调用hv.Text
的情况下标记每个条.问题似乎是hv.Text
不像其他元素一样接受data
参数. hv.Bars
,而不是x
和y
坐标.我的直觉是我应该能够做类似的事情
But I have no idea how I can label each bar without explicitly calling hv.Text
separately for every data point (bar). The problem seems to be that hv.Text
does not accept a data
argument like other elements e.g. hv.Bars
, instead just x
and y
coordinates. My intuition would be that I should be able to do something like
p * hv.Text(dat, kdims=['team'], vdims=['n_people_percent'])
对此表示感谢的任何帮助!
Any help with this appreciated!
推荐答案
像这样的 commit 将矢量化标签添加到hv.Labels
,因此请尝试:
Looks like this commit adds vectorized labels to hv.Labels
, so try:
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'])
这篇关于向Holoviews图中的每个数据点添加文本注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!