How to Make a Line Chart in Bokeh

Draw single and multiple lines in Bokeh, format a date axis, click the legend to hide lines, and add bands, steps and gaps.

To make a line chart in Bokeh, create a figure() and call p.line(x, y), then show(p). Each call to line() adds one line, and legend_label= gives it a legend entry. This post uses Bokeh 3.10.

Quick Example

Daily visits to a small website for 120 days, split by traffic source. Click a legend entry to hide that line.

import numpy as np
import pandas as pd
from bokeh.plotting import figure, show

rng = np.random.default_rng(21)
days = pd.date_range("2026-03-01", periods=120)
trend = np.linspace(0, 1, len(days))
weekend = np.where(days.dayofweek >= 5, 0.72, 1.0)
df = pd.DataFrame({
    "day": days,
    "search": ((420 + 380 * trend) * weekend + rng.normal(0, 30, 120)).round(),
    "direct": ((300 + 60 * trend) * weekend + rng.normal(0, 22, 120)).round(),
    "social": ((140 + 90 * np.sin(trend * 9)) + rng.normal(0, 18, 120)).round(),
})
colors = {"search": "#1971c2", "direct": "#e8590c", "social": "#2b8a3e"}

p = figure(title="Daily visits by traffic source", x_axis_type="datetime",
           height=420, sizing_mode="stretch_width", y_axis_label="Visits")
for source, color in colors.items():
    p.line(df["day"], df[source], color=color, line_width=2,
           legend_label=source.title())
p.legend.location = "top_left"
p.legend.orientation = "horizontal"
p.legend.click_policy = "hide"
p.y_range.start = 0
p.y_range.end = 1100
show(p)

Bokeh line chart of 120 days of website visits: search climbs from a March average of about 440 a day to 690 in June, direct stays near 300 and social swings between about 50 and 270

Search visits climb from a March average of about 440 a day to about 690 in June, direct visits stay close to 300, and social traffic rises and falls. The regular dips are weekends. The toolbar on the right pans, zooms with a box or the scroll wheel, saves a PNG, and resets the view.

How Do I Plot One Line?

Pass two equal-length sequences to line(). Without x_axis_type, the x-axis is numeric.

hours = np.arange(24)
load = 40 + 25 * np.sin((hours - 8) / 24 * 2 * np.pi) + rng.normal(0, 2, 24)

p = figure(title="Server load over one day", x_axis_label="Hour",
           y_axis_label="CPU (%)", height=320, sizing_mode="stretch_width")
p.line(hours, load, line_width=3, color="#7048e8")
show(p)

Bokeh line chart of server CPU load over 24 hours, lowest around 2:00 and peaking near 65 percent in the afternoon

Bokeh draws points in the order you give them. If a line zigzags back and forth, sort the data by x first.

Plot a Line From a DataFrame

Every glyph method accepts a source. Pass a DataFrame (or a ColumnDataSource) and name its columns as strings. A named index becomes a column too.

# March 1 is a Sunday, so the first "week" holds a single day. Drop it.
weekly = df.set_index("day").resample("W").sum().iloc[1:]

p = figure(title="Weekly search visits", x_axis_type="datetime", height=320,
           sizing_mode="stretch_width")
p.line("day", "search", source=weekly, line_width=2)
p.scatter("day", "search", source=weekly, size=8, fill_color="white", line_width=2)
show(p)

Bokeh line chart with circle markers showing weekly search visits climbing over the spring

The second call adds markers on top of the line. Use scatter() for markers: passing size to circle() has been deprecated since Bokeh 3.4.

resample("W") labels each week by the Sunday that ends it. Check the first and last rows after resampling: a partial week shows up as a drop that isn't real.

Format the Date Axis

x_axis_type="datetime" picks tick labels that change with the zoom level. To control them, set a DatetimeTickFormatter, which has one format string per time scale.

from bokeh.models import DatetimeTickFormatter, NumeralTickFormatter

p = figure(x_axis_type="datetime", height=320, sizing_mode="stretch_width")
p.line(df["day"], df["search"] * 1000, line_width=2)
p.xaxis.formatter = DatetimeTickFormatter(days="%b %d", months="%b %Y")
p.yaxis.formatter = NumeralTickFormatter(format="0.0a")  # 600000 -> 600.0k
show(p)

Bokeh line chart with month and day tick labels on the x-axis and y values abbreviated with a k

Line Styles

line_dash takes "solid", "dashed", "dotted", "dotdash", "dashdot", or a list of on and off lengths in pixels such as [12, 4]. line_width and line_alpha set thickness and opacity.

x = np.linspace(0, 10, 60)
p = figure(height=320, sizing_mode="stretch_width", y_range=(-0.5, 6.8))
for i, dash in enumerate(["solid", "dashed", "dotted", "dotdash", [12, 4]]):
    p.line(x, np.sin(x) * 0.4 + i * 1.3, line_dash=dash, line_width=3, color="#343a40")
    p.text(x=[0], y=[i * 1.3 + 0.5], text=[repr(dash)], text_font_size="12px")
show(p)

Five sine waves drawn with solid, dashed, dotted, dotdash and custom 12-on 4-off line styles

Add a Shaded Band Around a Line

varea() fills between two y series. Draw it before the line so the line sits on top.

roll = df.set_index("day")["search"].rolling(14, min_periods=14)
band = pd.DataFrame({"mean": roll.mean(), "std": roll.std()}).dropna()
band["low"] = band["mean"] - 2 * band["std"]
band["high"] = band["mean"] + 2 * band["std"]

p = figure(title="Search visits: 14-day mean and spread", x_axis_type="datetime",
           height=360, sizing_mode="stretch_width")
p.varea("day", "low", "high", source=band, fill_alpha=0.18, fill_color="#1971c2",
        legend_label="Mean ± 2 SD")
p.line("day", "mean", source=band, line_width=3, color="#1971c2",
       legend_label="14-day mean")
p.scatter(df["day"], df["search"], size=4, color="#868e96", legend_label="Daily")
p.legend.location = "top_left"
show(p)

Search visits with grey daily points, a blue 14-day rolling mean and a light blue band two standard deviations either side

The band shows how much daily values vary, which here is mostly the weekday and weekend gap. It isn't a confidence interval for the mean.

Step Lines and Gaps for Missing Data

step() holds each value until the next one, which suits prices, plan limits and other values that change at set moments. mode="after" draws the horizontal part after each point. A NaN in the data leaves a gap in a line.

months = pd.date_range("2025-01-01", periods=18, freq="MS")
price = np.repeat([9, 12, 12, 15, 15, 19], 3)
usage = 20 + np.arange(18) * 0.6 + rng.normal(0, 1.2, 18)
usage[7:10] = np.nan  # the meter was offline

p = figure(x_axis_type="datetime", height=340, sizing_mode="stretch_width")
p.step(months, price, mode="after", line_width=3, color="#c2255c",
       legend_label="Plan price ($)")
p.line(months, usage, line_width=3, color="#0b7285", legend_label="Usage (GB)")
p.legend.location = "top_left"
p.y_range.start = 0
show(p)

Step line of a plan price rising from 9 to 19 dollars and a usage line with a three month gap

Many Lines at Once

multi_line() takes a list of x arrays and a list of y arrays and draws them as one glyph, which is handy when you have dozens of series in one style.

paths = 100 + rng.normal(0.15, 2, (40, 90)).cumsum(axis=1)

p = figure(title="40 simulated price paths", height=340, sizing_mode="stretch_width")
p.multi_line([np.arange(90)] * 40, list(paths), line_alpha=0.25, color="#5f3dc4")
p.line(np.arange(90), np.median(paths, axis=0), line_width=3, color="#e8590c",
       legend_label="Median")
p.legend.location = "top_left"
show(p)

Forty faint purple simulated price paths with the median path in orange

Method Use it for
line() in a loop A few series, each with its own color and legend entry
multi_line() Many series in the same style
step() Values that change in jumps
varea() A filled range or band

Practical Tips

  • Set legend options after the first glyph with a legend_label. Before that, there is no legend to configure.
  • click_policy="mute" fades a line instead of removing it. Give the line a muted_alpha, such as muted_alpha=0.15.
  • To move the legend outside the plot, use p.add_layout(p.legend[0], "right").
  • To read values off the lines, add a hover tool with mode="vline".

Similar Topics