在Python Bokeh中填充线下的区域

5

如何在Bokeh中为一条线阴影区域添加色彩?

我有一个简单的线性图,想要在指定的颜色下填充线条下方的区域。

import pandas as pd
from bokeh.io import output_file, curdoc
from bokeh.plotting import figure, show
from bokeh.models import ColumnDataSource

output_file("layout.html")


df = pd.DataFrame({'date': ["1-1-2019", "2-1-2019", "3-1-2019", "4-1-2019", "5-1-2019", "6-1-2019", "7-1-2019", "8-1-2019", "9-1-2019", "10-1-2019"],
                   'cost': [10, 15, 20, 30, 25, 5, 15, 30, 35, 25]})

fig = figure(x_axis_type="datetime", toolbar_location='above', plot_width=1500)

plot_source = ColumnDataSource(data=dict(date=pd.to_datetime(df["date"]),
                                         cost=df["cost"]))

line_plot = fig.line("date", "cost", source=plot_source, line_width=2, color="#00CED1")

show(fig) 

因此,它在下面的图像中看起来像一个绿色区域。

enter image description here

我检查了Pathces字形函数,但我不清楚它的含义。感谢任何帮助!


也许是Bands?https://docs.bokeh.org/en/latest/docs/user_guide/annotations.html#bands - JohanC
2个回答

6
也许可以像这样:

可能有以下解决方案:

band = Band(base='date', upper='cost', source=plot_source, level='underlay',
            fill_alpha=0.2, fill_color='#55FF88')
fig.add_layout(band)

编辑:看起来fill_alpha=0.2, fill_color='#55FF88'更接近示例

完整的示例如下:

import pandas as pd
from bokeh.io import output_file, curdoc
from bokeh.plotting import figure, show
from bokeh.models import ColumnDataSource, Band

output_file("layout.html")
df = pd.DataFrame({'date': ["1-1-2019", "2-1-2019", "3-1-2019", "4-1-2019", "5-1-2019", "6-1-2019", "7-1-2019", "8-1-2019", "9-1-2019", "10-1-2019"],
                   'cost': [10, 15, 20, 30, 25, 5, 15, 30, 35, 25]})
fig = figure(x_axis_type="datetime", toolbar_location='above', plot_width=1500)
plot_source = ColumnDataSource(data=dict(date=pd.to_datetime(df["date"]),
                                         cost=df["cost"]))
line_plot = fig.line("date", "cost", source=plot_source, line_width=2, color="#00CED1")
band = Band(base='date', upper='cost', source=plot_source, level='underlay',
            fill_alpha=0.2, fill_color='#55FF88')
fig.add_layout(band)
show(fig)

生成的图表:生成的图表 附注:Band标注不支持图例。如需图例,请按照@bigreddot的建议,将Band替换为varea字符。在您的代码中:
fig.varea(source=plot_source, x="date", y1=0, y2="cost",
          alpha=0.2, fill_color='#55FF88', legend_label="cost")

这将返回一个空的布局。 - isabella
错误与bokeh版本有关,更新后问题得到解决。谢谢! - isabella
是否有一种方法可以为Band对象添加图例? - isabella

6

Band 是一个选项,但是使用varea 更好,因为它是一种字形而不是注释,并且还支持varea_stack 的堆叠,如果你需要堆叠。

from bokeh.plotting import figure, show

p = figure(plot_width=400, plot_height=400)

p.varea(x=[1, 2, 3, 4, 5],
        y1=0, y2=[1, 4, 2, 2, 3], alpha=0.6)

show(p)

enter image description here


它返回以下错误:"AttributeError:'Figure'对象没有'varea'属性"。 - isabella
错误是由于bokeh版本的问题,更新后,它也能正常工作了。非常感谢您的帮助! - isabella
相比于带(band),如果想要为绘图添加图例(legend),这种方法更好。 - isabella

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