Skip to main content
 首页 » 编程设计

python之Bokeh 中贝塞尔曲线之间的填充区域

2024年09月07日8insus

我正在尝试使用 bokeh 创建桑基图,目前正在尝试找出如何填充两条 Bezier 曲线之间的区域。这是否可能,或者是否有任何替代方法可以在不添加单独的 Bezier 字形的情况下实现这一目标?

下面的示例代码——目标是用橙色填充曲线之间的区域。

from bokeh.models import Range1d, Plot, LinearAxis 
from bokeh.models.glyphs import Bezier 
from bokeh.io import show 
 
plot = Plot(title=None, x_range=Range1d(0, 1), y_range=Range1d(-1, 1), plot_width=300, plot_height=300) 
 
glyph = Bezier(x0=0, y0=0, x1=1, y1=1, cx0=0.5, cy0=0.01, cx1=0.5, cy1=0.99, line_color="orange", line_width=2) 
glyph2 = Bezier(x0=0, y0=-1, x1=1, y1=0.5, cx0=0.5, cy0=-0.99, cx1=0.5, cy1=0.49, line_color="orange", line_width=2) 
 
g1 = plot.add_glyph(glyph) 
g2 = plot.add_glyph(glyph2) 
 
xaxis = LinearAxis() 
plot.add_layout(xaxis, 'below') 
 
yaxis = LinearAxis() 
plot.add_layout(yaxis, 'left') 
 
show(plot) 

请您参考如下方法:

从 Bokeh 0.13.0 开始,无法使用任何内置功能在两条贝塞尔曲线之间进行填充。目前,要实现这一点,您必须编写某种 custom extension class使用 HTML Canvas JavaScript API 获取您的输入数据并绘制曲线和填充。

否则,如果您能够将曲线表示为显式折线而不是贝塞尔曲线,那么下一个最接近的是 Band注解。假设一个包含 x、y_mean 和 y_std 的数据框,您可以执行以下操作:

df['lower'] = df.y_mean - df.y_std 
df['upper'] = df.y_mean + df.y_std 
 
source = ColumnDataSource(df.reset_index()) 
 
band = Band(base='x', lower='lower', upper='upper', source=source,  
            level='underlay', fill_alpha=1.0, line_width=1, line_color='black') 
p.add_layout(band) 

或许可以考虑添加一个更通用的波段,它可以通过贝塞尔曲线等方式指定。随意制作GitHb feature request issue