How to add a title to a bokeh plot ?


Introduction

Bokeh is an interactive visualization library for modern web browsers that allows you to create elegant, versatile, and visually appealing plots and dashboards.

In this tutorial, we will learn how to add a title to a Bokeh plot in Python.

Creating a bokeh plot

As an illustration, let's attempt to plot a cosine function:

from bokeh.plotting import figure, show

p = figure(width=400, height=400)

X = np.linspace(-6, 6, 40)
Y = np.cos(X)

p.line(X, Y, color="coral", line_width=2)

# show the results
show(p)

How to add a title to a bokeh plot ?
How to add a title to a bokeh plot ?

Adding a title to a Bokeh Plot in Python

To add a title to our plot, we can use the title property of the figure object:

from bokeh.plotting import figure, show

p = figure(title="Cosine Function", width=400, height=400)

X = np.linspace(-6, 6, 40)
Y = np.cos(X)

p.line(X, Y, color="coral", line_width=2)

show(p)

How to add a title to a bokeh plot ?
How to add a title to a bokeh plot ?

Title customization

We can also customize the title font size and color using the title_text_font_size and title_text_color properties:

from bokeh.plotting import figure, show

p = figure(width=400, height=400)

p.title.text = "Cosine Function"
p.title.align = "center"
p.title.text_color = "Coral"
p.title.text_font_size = "14px"
p.title.background_fill_color = "black"

X = np.linspace(-6, 6, 40)
Y = np.cos(X)

p.line(X, Y, color="coral", line_width=2)

show(p)

How to add a title to a bokeh plot ?
How to add a title to a bokeh plot ?

Additional Examples

Here are some additional examples to further illustrate the point:

import numpy as np

from bokeh.io import curdoc, show
from bokeh.models import Line, ColumnDataSource, Grid, LinearAxis, Plot

X = np.linspace(-6, 6, 40)
Y = np.cos(X)

source = ColumnDataSource(dict(x=X, y=Y))

plot = Plot(title='Cosine Function', width=300, height=300, min_border=0, toolbar_location=None)

glyph = Line(x="x", y="y", line_color="#3288bd", line_width=3)
plot.add_glyph(source, glyph)

xaxis = LinearAxis()
plot.add_layout(xaxis, 'below')

yaxis = LinearAxis()
plot.add_layout(yaxis, 'left')

plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))

curdoc().add_root(plot)

show(plot)

How to add a title to a bokeh plot ?
How to add a title to a bokeh plot ?

References

Links Site
Adding annotations docs.bokeh.org
Circle docs.bokeh.org
First steps 1: Creating a line chart docs.bokeh.org
Image

of