Bokeh绘图的条件背景色

4

我有一个pandas数据帧,其中包含一个布尔列,如下所示:

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

我希望您能在y轴上绘制B的值,在x轴上绘制A的值,并且根据C的条件背景色进行条件性着色。我希望效果类似于下面的图片:simulated result
我可以使用框注释实现这个吗?
1个回答

3

是的,可以使用BoxAnnotationleftright参数来实现:

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)。但是,您还没有为此情况指定适当的行为。

enter image description here


谢谢,它可以工作了。我不得不做一些调整,因为我的真实数据集有日期时间索引,但现在没问题了,非常感谢。 - bAN

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接