python-3.x - 如何根据散景中的值添加注释
问题描述
当计数值为“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
解决方案
您可以使用 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)
推荐阅读
- java - 获取意外令牌:在尝试输出列值时出现错误
- node.js - Docker - Windows 上容器的 IP 地址
- javascript - Javascript 不适用于新添加的 HTML
- html - 将视频响应添加到表单(最好是 typeform)
- java - 通过 TCP 套接字发送消息 - Java(已关闭)
- javascript - ReactJS 中的全局函数告诉我“不是函数”
- r - ShinyApp 操作按钮:单击与双击的不同值
- javascript - 试图使嵌套问题动态显示... C# ASP.Net Database First,
- php - 在 MySQL 中处理数千条记录
- android - Android 模拟器浏览器无法访问主机文件上设置的 localhost 子域