How to add graph slider in Bokeh

Bokeh is a Python library used for creating interactive visualizations in a web browser. It provides powerful tools that offer flexibility, interactivity, and scalability for exploring various data insights.

What is a graph slider?

A graph slider is a user interface widget that puts the user in control by allowing them to interactively adjust the plots. It offers run time changes in numeric variables. You can insert sliders in the graphs and explore the variations while changing the values of each variable between a specific range.

The graph changes according to the slider values.
The graph changes according to the slider values.

Why do we need a graph slider?

Color sliders are widely used to allow users to create their own color that suits their requirements. This interactive feature puts the user in control and improves the overall user experience.

A graph slider is a crucial feature in various domains highly focused on visuals and user interactivity. Hence, it is integrated into widely used software that help to conduct analysis through data visualization. Some other applications are also mentioned below.

  • Financial planning: Adjust variables like investment return rates, profit rate, and inflation rate to see the impact on financial goals.

  • Gaming and simulation: Incorporate games to give user control, like adjusting speed and acceleration in racing games.

  • BCG matrix: Observe sales, profit, and demand over the years to categorize products.

  • Space flights and plane coordinates: Use the sine function to keep track of the space coordinates and flights. We can track patterns to analyze risk and probabilities by adjusting quantifiable dependency variables.

Let's plot a sine function and manipulate it using difference dependency factors as a slider object.

Required imports

Import the necessary modules from the bokeh library.

import numpy as np
from bokeh.io import output_file, save
from bokeh.layouts import column
from bokeh.models import ColumnDataSource, CustomJS, Slider
from bokeh.plotting import curdoc, figure, show
  • numpy: To do numerical computations and generate data for the graph plot.

  • bokeh.io: To control the output and display of the plots. We specifically import output_file and save methods from.

  • bokeh.layouts: To create complex and structured layouts for our visualizations. We specifically import column to create a vertical layout by stacking multiple objects vertically.

  • bokeh.models: To create highly customized visualizations in Bokeh. We specifically import ColumnDataSource, CustomJS and Slider from it.

  • bokeh.plotting: To create and customize plots without working directly with the lower-level Bokeh models. We specifically import figure and show from it.

Example code

In this example, we use the sliders to change the amplitude, frequency, phase, and offset of a simple sine function and observe its effect.

import numpy as np
from bokeh.io import output_file, save
from bokeh.layouts import column
from bokeh.models import ColumnDataSource, CustomJS, Slider
from bokeh.plotting import figure, show

#generate random data
x = np.linspace(0, 10, 500)
y = np.sin(x)

source = ColumnDataSource(data=dict(x=x, y=y))

#create figure
myPlot = figure(y_range=(-10, 10), 
              width=660, 
              height=380, 
              toolbar_location=None, 
              background_fill_color='white')

#create line
myPlot.line('x', 'y', 
            source=source, 
            line_width=3, 
            line_alpha=0.6)

#create sliders
amp    = Slider(start=0.1, end=10, value=2, step=.1, title="Amplitude", bar_color='yellow')
freq   = Slider(start=0.1, end=10, value=2, step=.1, title="Frequency", bar_color='purple')
phase  = Slider(start=-6.4, end=6.4, value=0, step=.1, title="Phase" , bar_color='blue')
offset = Slider(start=-9, end=9, value=0, step=.1, title="Offset" , bar_color='green')

#javaScript callback
callback = CustomJS(args=dict(source=source, amp=amp, freq=freq, phase=phase, offset=offset),
                    code="""
    const A = amp.value
    const k = freq.value
    const p = phase.value
    const B = offset.value

    const x = source.data.x
    const y = Array.from(x, (x) => B + A*Math.sin(k*x+p))
    source.data = { x, y }
""")

#call callback when change in slider
amp.js_on_change('value', callback)
freq.js_on_change('value', callback)
phase.js_on_change('value', callback)
offset.js_on_change('value', callback)

#display output
output_file("output.html")
show(column(myPlot,amp, freq, phase, offset))
Creating a graph slider.

Code explanation

  • Lines 1–5: Import all the necessary libraries and modules.

  • Line 8: Generates 500 equally spaced values using linspace() for a range of 0 to 10 on the x-axis.

  • Line 9: Computes the sine of each x-axis value using the sin function and get the y-axis values.

  • Line 11: Use ColumnDataSource to create a source and pass the data dictionary, containing the x-axis and corresponding y-axis values, as a parameter.

  • Lines 14–18: Create a plot using figure() and specify the axes' range, width, height, toolbar, and fill color of the plot as parameters.

  • Lines 21–24: Create a plot line using line() and specify the x and y coordinates, source, line width, and transparency as parameters.

  • Lines 27–30: Create Slider objects for amplitude amp, frequency freq, phase phase, and offset offset and specify the properties.

    • start : the minimum and starting range value of the bar.

    • end : the maximum and ing range value of the bar.

    • value : to set the initial value for the default plot.

    • step : to specify the bar precision for moving ahead or backward.

    • title : the label that appears along with the bar.

    • bar_color : the color fill of the bar that increases and decreases dynamically.

  • Lines 33–42: Create a callback with JavaScript code using CustomJS that assigns the amplitude, frequency, phase, and offset values to the variables and returns new x and y coordinates.

Note : Calculate the y-axis values for corresponding x-axis values using :

offset + amplitude * Math.sin(frequency * x-axis value + phase)).

  • Lines 46–49: Use js_on_change() to assign the JavaScript callback function to the value change event of each slider. Whenever the bars are moved, the callback function is triggered.

  • Lines 52–53: Set the output to output.html to specify the endpoint where the display will appear and use show() to display the graph slider.

Code output

It displays a sine graph with sliders for adjusting the amplitude, frequency, phase, and offset of it. When we move the sliders, the graph changes accordingly.

Common query

Question

Can we remove phase as a slider object without getting an error?

Show Answer

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved