Skip to main content
 首页 » 编程设计

python之Bokeh 图条件背景色

2024年10月01日9shihaiming

我有一个 pandas 数据框,其中包含这样一个 bool 列:

| A | B |   C   | 
| 1 | 3 | True  | 
| 2 | 4 | True  | 
| 3 | 4 | False | 
| 4 | 1 | False | 
| 5 | 2 | True  | 

我想用基于 C 的条件背景色绘制 Y 上的 B 值和 X 上的 A 值 我的意思是这样的:

我可以使用方框注释来做到这一点吗?

请您参考如下方法:

是的,可以使用 BoxAnnotation 的 left 和 right 参数:

import pandas as pd 
from bokeh.plotting import figure, show, output_file, output_notebook 
from bokeh.models import BoxAnnotation 
 
output_notebook() 
 
# dummy data  
df = pd.DataFrame({"A": [1, 2, 3, 4, 5, 6], 
                   "B": [3, 4, 4, 1, 2, 3], 
                   "C": [True, True, False, False, True, True]}) 
print(df) 
 
>>>     A   B   C 
 
    0   1   3   True 
    1   2   4   True 
    2   3   4   False 
    3   4   1   False 
    4   5   2   True 
    5   6   3   True 

为了简化,我在这里添加了另一行以获得用于绘图的 True 计数。

现在,获取包含 True 的连续行:

df["cons"] = (df["C"].diff(1) != 0).astype('int').cumsum()  
mask = df["cons"] % 2 == 1 
 
cons_indices = df[mask].groupby("cons").apply(lambda x: x.A.values) 
print(cons_indices) 
 
>>> cons 
    1    [1, 2] 
    3    [5, 6] 
    dtype: object 

最后绘制它:

p = figure(title="Annotations") 
p.line(df["A"], df["B"]) 
 
for cons_index in cons_indices: 
    low_box = BoxAnnotation(left=cons_index.min(), right=cons_index.max(), fill_color="Blue") 
    p.add_layout(low_box) 
 
show(p) 

该解决方案还不处理单个 True(非连续 True)值。但是,您尚未为此场景指定适当的行为。