首页 > 解决方案 > 如何根据散景中的值添加注释

问题描述

当计数值为“0”时,我希望能够显示“NO DATA”。例如,对于草莓,图表中应显示“NO DATA”。

    from bokeh.io import show, output_file
    from bokeh.plotting import figure
    output_file("bar_basic.html")
    fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
    counts = [5, 3, 4, 2, 4, 0]
    p = figure(x_range=fruits, plot_height=350, title="Fruit Counts")
    p.vbar(x=fruits, top=counts, width=0.9)
    p.y_range.start = 0
    show(p)

例如,对于上述数据,图表应如下所示:example vbar with NO DATA

标签: python-3.xbokeh

解决方案


您可以使用 Pandas 选择计数值为“0”的数据。这个新数据框可用于创建另一个 ColumnDataSource 以用于 LabelSet 以在图中显示文本“NO DATA”。

from bokeh.io import show, output_file
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource, LabelSet
import pandas as pd

output_file("bar_basic.html")
fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries']
counts = [5, 3, 4, 2, 4, 0]
df = pd.DataFrame.from_dict({'fruits': fruits, 'counts': counts})
source = ColumnDataSource(df)
p = figure(x_range=fruits, plot_height=350, title="Fruit Counts")
p.vbar(x='fruits', top='counts', source=source, width=0.9)
df_nodata = df.loc[df['counts'] == 0]
pd.options.mode.chained_assignment = None
df_nodata.loc[:, 'text'] = 'NO DATA'
source_nodata = ColumnDataSource(df_nodata)
labels = LabelSet(x='fruits', y=1, text='text', text_align='center', source=source_nodata)
p.add_layout(labels)
p.y_range.start = 0
show(p)

推荐阅读