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')
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'
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:

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With