How can Bokeh library be used to visualize twin axes in Python?

Bokeh is a Python package that helps in data visualization. It is an open source project. Bokeh renders its plot using HTML and JavaScript. This indicates that it is useful while working with web-based dashboards.

Matplotlib and Seaborn produce static plots, whereas Bokeh produces interactive plots. This means when the user interacts with these plots, they change accordingly.

Plots can be embedded as output of Flask or Django enabled web applications. Jupyter notebook can also be used to render these plots.

Installation

Installation of Bokeh on Windows command prompt:

pip3 install bokeh

Installation of Bokeh on Anaconda prompt:

conda install bokeh

Creating Twin Axes Plot

Twin axes allow you to display two different datasets with different scales on the same plot. One axis appears on the left, and another on the right side of the plot.

Example

Let us create a twin axis plot with sine wave and linear data −

from numpy import pi, arange, sin, linspace
from bokeh.plotting import output_file, figure, show
from bokeh.models import LinearAxis, Range1d

# Generate data
x = arange(-2.5*pi, 2.5*pi, 0.15)
y = sin(x)
y2 = linspace(0, 176, len(y))

# Create figure with initial y-range for first dataset
my_fig = figure(title='Twin Axis Plot', width=500, height=400, y_range=(-1.2, 1.2))

# Plot first line (sine wave) on left y-axis
my_fig.line(x, y, color="blue", legend_label="sin(x)", line_width=2)

# Add second y-axis range on the right
my_fig.extra_y_ranges = {"y2": Range1d(start=0, end=200)}
my_fig.add_layout(LinearAxis(y_range_name="y2"), 'right')

# Plot second line on right y-axis
my_fig.line(x, y2, color="red", y_range_name="y2", legend_label="Linear", line_width=2)

# Configure legend
my_fig.legend.location = "top_left"

# Output to HTML file
output_file("twin_axis_plot.html")
show(my_fig)

Output

1.0 0.5 0.0 -0.5 -1.0 200 150 100 50 0 -5 0 5 10 Twin Axis Plot sin(x) Linear

How It Works

The key steps to create twin axes in Bokeh are:

  • Primary axis: Set the initial y_range when creating the figure
  • Secondary axis: Define extra_y_ranges dictionary with a named range
  • Add axis: Use add_layout(LinearAxis()) to add the second y-axis
  • Plot data: Specify y_range_name parameter for the secondary dataset

Key Parameters

  • extra_y_ranges: Dictionary defining additional y-axis ranges
  • LinearAxis: Creates a linear axis with specified range name
  • y_range_name: Associates plot elements with specific y-axis
  • add_layout: Adds axis to 'left' or 'right' side of the plot

Conclusion

Twin axes in Bokeh allow visualization of two datasets with different scales on the same plot. Use extra_y_ranges and LinearAxis to create secondary y-axes, and specify y_range_name to associate data with the correct axis.

Updated on: 2026-03-25T15:06:27+05:30

325 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements