向 Holoviews 图中的每个数据点添加文本注释
Add text annotations to each data point in Holoviews plot
在 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%')
但我不知道如何在不为每个数据点(条)分别显式调用 hv.Text
的情况下标记每个条。问题似乎是 hv.Text
不像其他元素那样接受 data
参数,例如hv.Bars
,而只是 x
和 y
坐标。我的直觉是我应该能够做类似
的事情
p * hv.Text(dat, kdims=['team'], vdims=['n_people_percent'])
感谢任何帮助!
看起来像这样 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'])
在 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%')
但我不知道如何在不为每个数据点(条)分别显式调用 hv.Text
的情况下标记每个条。问题似乎是 hv.Text
不像其他元素那样接受 data
参数,例如hv.Bars
,而只是 x
和 y
坐标。我的直觉是我应该能够做类似
p * hv.Text(dat, kdims=['team'], vdims=['n_people_percent'])
感谢任何帮助!
看起来像这样 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'])