15

I ran into a very seemingly simple problem when using the bokeh plotting package in python.

I wanted to set the title of a bokeh figure from outside of the usual figure constructor, but I get a strange error.

Here is the code.

from bokeh.plotting import figure
p = figure()
p.title = 'new title'

But when I tried this code, I get an error message:

ValueError: expected an instance of type Title, got new plot of type str

So it seems like I need to create a Title object or something to pass to the figure. However in the bokeh documentation there is no mention of how to set the title. There is only mention of how to change the title font or the title color, etc.

Does anyone know how to set the title of the plot from outside of the usual figure(title='new title')

krishnab
  • 9,270
  • 12
  • 66
  • 123

2 Answers2

30

To simply change the title without constructing a new Title object, you can set the figure's title.text attribute:

from bokeh.plotting import figure
p = figure()
p.title.text = 'New title'
Wesley Hill
  • 1,789
  • 1
  • 16
  • 27
12

Edit: Note that the solution in this answer will not work in bokeh server due to a known bug. This answer below will work and is more pythonic.


You have to assign an instance of Title to p.title. Since, we are able to investigate the types of things in python using the function type, it is fairly simple to figure out these sorts of things.

> type(p.title) 
bokeh.models.annotations.Title

Here's a complete example in a jupyter notebook:

from bokeh.models.annotations import Title
from bokeh.plotting import figure, show
import numpy as np
from bokeh.io import output_notebook
output_notebook()
x = np.arange(0, 2*np.pi, np.pi/100)
y = np.sin(x)
p = figure()
p.circle(x, y)
t = Title()
t.text = 'new title'
p.title = t
show(p)

outputs the following chart with the title set to new title:

example output

Thomas
  • 4,696
  • 5
  • 36
  • 71
Haleemur Ali
  • 26,718
  • 5
  • 61
  • 85
  • Cool, thanks for the info. I was looking at the source code to figure it out, but was not clear on how to set it. Thanks for the example. – krishnab Dec 09 '17 at 23:18