How to add color 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 color slider?

A color slider is a user interface widget that allows adjusting the color values. It provides interactivity and lets the user explore the variations of red, green, and blue and achieve the desired visual aesthetics.

It has a color window and three independent R, G, and B sliders, ranging from 0 to 255. When the sliders are moved, the resultant color shows on the window.

A color slider.
A color slider.

Why do we need a color 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.

Use color slider to create your own colors,
Use color slider to create your own colors,

A color slider is a crucial feature in various domains highly focused on visuals and user interactivity. Hence, it is integrated into widely used software relevant to data visualization.

  • Graphic designing software: Extensively use the color slider to adjust colors for various design elements and create digital artworks, e.g., Adobe Illustrator.

  • Gaming and user interface: Incorporate color sliders into gaming interfaces to choose skin tones, hair colors, or clothing shades to create personalized characters.

  • Image processing software: Manipulate color sliders to adjust to exposure, white balance, saturation, or specific color channels, e.g., Adobe Lightroom.

  • Interior designing software: Use a color slider to simulate color schemes for walls, furniture, and decor elements.

Required imports

Import the necessary modules from bokeh library.

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
from bokeh.themes import Theme

  • 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 curdoc, figure and show from it.

  • bokeh.themes: To apply themes and control visual attributes such as colors, fonts, grid lines, and axes.

Example code

In this example, we create a color slider and use R, G, and B sliders to create colors.

from bokeh.layouts import column
from bokeh.models import ColumnDataSource, CustomJS, Slider
from bokeh.plotting import curdoc, figure, show
from bokeh.themes import Theme
from bokeh.io import output_file, save

color = R, G, B = (164, 125, 226)
text_color = (255, 255, 255)

# create a data source to enable refreshing of fill & text color
source = ColumnDataSource(data=dict(color=[color], text_color=[text_color]))

# create first plot, as a rect() glyph and centered text label, with fill and text color taken from source
myPlot = figure(x_range=(-8, 8), y_range=(-4, 4),
           width=650, height=300,
           title='Create your own colors! Move the sliders to change')

myPlot.rect(0, 0, width=18, 
           height=10, 
           fill_color='color', 
           line_color = 'black', 
           source=source)

myPlot.text(0, 0, text='color', 
           text_color='text_color',
           alpha=0.6667, 
           text_font_size='50px', 
           text_baseline='middle',
           text_align='center', 
           source=source)

red = Slider(title="R", start=0, end=255, value=R, step=1)
green = Slider(title="G", start=0, end=255, value=G, step=1)
blue = Slider(title="B", start=0, end=255, value=B, step=1)

callback = CustomJS(args=dict(source=source, red=red, blue=blue, green=green), 
 code="""
    function toHex(c) {
        const hex = c.toString(16)
        return hex.length == 1 ? "0" + hex : hex
    }

    const R = red.value | 0
    const G = green.value | 0
    const B = blue.value | 0

    const color = "#" + toHex(R) + toHex(G) + toHex(B)
    const text_color = ((R > 127) || (G > 127) || (B > 127)) ? '#000000' : '#ffffff'
    source.data = { color: [color], text_color: [text_color] }
""")

red.js_on_change('value', callback)
blue.js_on_change('value', callback)
green.js_on_change('value', callback)

# theme everything for a cleaner look
curdoc().theme = Theme(json={
    "attrs": {
        "Plot": { "toolbar_location": None },
        "Grid": { "grid_line_color": None },
        "Axis": {
            "axis_line_color": None,
            "major_label_text_color": None,
            "major_tick_line_color": None,
            "minor_tick_line_color": None,
        },
    },
})

output_file("output.html")
show(column(myPlot,red, green, blue))
Creating a color slider.

Code explanation

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

  • Lines 7–8: Specify a default color for the slider and the text that shows the selected RGB values on the color window.

  • Line 11: Use ColumnDataSource to create a data source and pass the selected colors as parameters.

  • Lines 14–16: Create a plot and specify the axes' range, width, height, and title of the plot.

  • Lines 18–22: Create a rectangular glyph using rect() and specify the dimensions, line color, and fill color taken from the source.

  • Lines 24–30: Create a text label using text() and specify its styling properties.

  • Lines 32–34: Create Slider objects for red, green, and blue and specify the title, range, value, and step size for each.

  • Lines 36–50: Create a callback with JavaScript code using CustomJS that assigns the values to R, G, and B and concatenates them to create the hexadecimal string. If any value exceeds 127, it sets the text color to black; otherwise, it is white.

  • Lines 52–54: Use js_on_change() to assign the JavaScript callback function to the value change event of each slider.

  • Lines 56–64: Set the theme current document using curdoc() by modifying the visual attributes according to the need. In this case, we remove the grid and axis lines' colors for a cleaner look.

  • Lines 69–70: Set the output to output.html to specify the endpoint where the display will appear and use show() to display the color slider.

Code output

This is a color slider with the default color set to (164,125,226) as specified in the code. If any value exceeds 127, it sets the text color to black; otherwise, it is white.

Test your understanding

Match The Answer
Select an option from the left-hand side

R = 201 G = 210 B = 226

#c9d2e2 text color : black

R = 86 G = 78 B = 80

#564e50 text color : black

#564e50 text color : white

#c9d2e2 text color : white


Free Resources

Copyright ©2024 Educative, Inc. All rights reserved