Open In App

Bokeh – Annotations and Legends

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Prerequisites: Bokeh

Bokeh includes several types of annotations to allow users to add supplemental information to their visualizations. Annotations are used to add notes or more information about a topic. Annotations can be titles, legends, Arrows, bands, labels etc.

Adding legends to your figures can help to properly describe and define it. Hence, giving more clarity. Legends in Bokeh are simple to implement. They can be basic, automatically grouped, manually mentioned, explicitly indexed and also interactive.

Given below is the examples to help you understand better:

Example: Basic legends 

The legend_label parameter is used to add a basic label to any one of the glyph.

Python3




from bokeh.plotting import figure, output_file, show
  
x = [val for val in range(10)]
y = [val for val in range(0, 20, 2)]
  
output_file("basiclegend.html")
  
p = figure()
  
p.line(x, y, legend_label="My Red Line", line_color="red")
p.line(y, x, legend_label="My Orange Line", line_color="orange")
p.line(y[::-1], x, legend_label="My Green Line", line_color="green")
  
show(p)


Output:

Example 2: Automatic Grouping can be used when we want to group multiple legend items to be grouped into one.

Python3




from bokeh.plotting import figure, output_file, show
from bokeh.models import ColumnDataSource
  
p = figure(x_range=(0.5, 2.5), y_range=(0.5, 2.5))
  
source = ColumnDataSource(dict(
    x=[1, 1, 2, 2, 1.5],
    y=[1, 2, 1, 2, 1.5],
    color=['red', 'red', 'red', 'red', 'blue'],
    label=['corner', 'corner', 'corner', 'corner', 'center']
))
p.circle(x='x', y='y', radius=0.05, color='color',
         legend_group='label', source=source)
  
output_file("AutomaticGrouping.html")
  
show(p)


Output:

Example 3: Interactive legends

Python3




from bokeh.plotting import figure, output_file, show
  
p = figure()
  
x = [x for x in range(1, 11)]
colors = ['red', 'green', 'blue', 'yellow']
for i in range(2, 6):
    p.line(x, [val*i for val in x], line_width=2, color=colors[i-2],
           alpha=0.8, legend_label='Multiples of {}'.format(i))
  
p.legend.location = "top_left"
p.legend.click_policy = "hide"
output_file("interactive_legend.html")
  
show(p)


Output:



Last Updated : 17 Dec, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads