python - 如何根据散景中的y填充不同颜色的区域
问题描述
当 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)
解决方案
字形是连续的VArea
,但可以通过将一些区域折叠为 0 区域块来使其看起来像单独的部分,方法是使用变换制作y1
和y2
相同。
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)
推荐阅读
- c# - 使用反射将属性设置为其类型的代理对象
- mysql - 更新专用于特定订单的列
- php - 单击电子邮件中的激活链接后的 USER 更新
- json - Json 模式验证器,如何验证键是否不是静态的
- javascript - 仅当 display=none(显示 div)时验证输入检查
- ssl - https 重定向有时只有效
- git - 我可以关闭 git checkout 的“你的分支在 N 次提交之前的'origin/whatever'”消息吗?
- javascript - 如何使用ajax将javascript二维数组传输到asp mvc中的控制器?
- c++ - 中心化公平 RW 自旋锁
- python - 将在 python 中创建的表导入到 docx