如何在Bokeh中根据y填充不同颜色的区域。

问题描述 投票:1回答:1

当y>=0时,填充颜色应该是绿色的,当y<=0时,填充颜色应该是红色的。 你可以在Matplotlib中使用fill_between中的'when'变量来实现这个功能。Bokeh有类似的功能吗?

from bokeh.plotting import figure, output_file, show
import numpy as np

strike1 = 20 #Long Call
premium1 = 0.5
price = np.arange(15,25,0.01)
contracts = 1

def long_call(price, strike1, premium1, contracts):
    P = []
    for i in price:
        P.append((max(i - strike1, 0) - premium1) * (contracts * 100))
    return np.array(P)


# output to static HTML file
output_file("lines.html")

# create a new plot with a title and axis labels
p = figure(title="Option Payoff", x_axis_label='Underlying Price ($)', y_axis_label='Profit/Loss ($)')

# add a line renderer with legend and line thickness
p.line(x, y, line_width=2)
p.varea(x=x, y1=y, fill_alpha=1, fill_color='#3cb371')

# show the results
show(p)
python bokeh
1个回答
2
投票

VArea 字形是连续的,但也可以通过将一些区域折叠成一个0面积的块,使其看起来像独立的部分,通过使 y1y2 同样的一个转变。

import math

from bokeh.models import ColumnDataSource, CustomJSTransform
from bokeh.plotting import figure, show
from bokeh.transform import transform

N = 100
ds = ColumnDataSource(dict(x=[i / 10 for i in range(N)],
                           y=[math.sin(i / 10) for i in range(N)]))
p = figure()
p.line('x', 'y', source=ds, line_width=3)
p.varea(x='x', y1=transform('y', CustomJSTransform(v_func="return xs.map(x => x > 0 ? x : 0)")),
        y2=0, source=ds, color='green', fill_alpha=0.5)
p.varea(x='x', y1=transform('y', CustomJSTransform(v_func="return xs.map(x => x < 0 ? x : 0)")),
        y2=0, source=ds, color='red', fill_alpha=0.5)

show(p)
© www.soinside.com 2019 - 2024. All rights reserved.