Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill an area under a line in Python Bokeh

Tags:

python

bokeh

How to shade the area under a line in Bokeh?

I have a simple line plot as follows and I want to fill an under a line in a specified color.

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) 

So it will look like a green area in the image below.

enter image description here

I checked Pathces glyph function however I am not clear about it. Appreciate any help!

like image 447
isabella Avatar asked Dec 18 '22 15:12

isabella


1 Answers

Maybe something like:

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

Edit: fill_alpha=0.2, fill_color='#55FF88' seem to be closer to the example

A complete example looks like:

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)

The generated plot: Generated plot

PS: The Band annotation doesn't have support for the legend. To get a legend, replace the Band with the varea glyph as proposed by @bigreddot. In your code:

fig.varea(source=plot_source, x="date", y1=0, y2="cost",
          alpha=0.2, fill_color='#55FF88', legend_label="cost")
like image 132
JohanC Avatar answered Dec 26 '22 19:12

JohanC