2017-04-07 92 views
1

我有一個包含這樣一個布爾列大熊貓數據幀:散景情節條件背景顏色

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

我想與基於條件的背景顏色上Y和A上繪製X B的值C 我的意思是這樣的:simulated result

我可以使用框註釋來做到嗎?

回答

1

是的,有可能使用的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

+0

由於它的工作原理,不得不調整了一下,因爲我真正的數據集有日期時間指數,但它現在是好的,非常感謝 – bAN