Using sliders to control opacity of background images


I have a graph that I’ve created where I want there to be two images, side-by-side, that serve as the background of the graph. However, I also want the user to be able to control whether or not those backgrounds are visible and how visible they are if they are visible, so I figured that using Sliders was the best way to do this.

After many hours noodling around, I finally figure out one way to do this; however, I’m wondering if perhaps there isn’t a more elegant and/or simple way to do it.

# import Python packages
import pandas as pd

from bokeh.plotting import figure, output_file, show
from bokeh.layouts import column, row
from bokeh.models import Slider

# Bokeh setup
p1 = figure(width=1500, height=500, tools="pan,wheel_zoom,reset")
image_top = 'top.jpg'
image_bot = 'bot.jpg'
p1.image_url(url = [image_top],  x=360, y=0, w=14000, h=10000, anchor="bottom_left", alpha=1, name='top_image')
p1.image_url(url = [image_bot],  x=-500, y=0, w=14000, h=10000, anchor="bottom_right", alpha=1, name='bot_image')

# Add sliders that control how opaque the background images are
bg_top = Slider(start=0, end=1, value=1, step=0.01, title="Opacity of Right Image")
bg_bot = Slider(start=0, end=1, value=1, step=0.01, title="Opacity of Left Image")

# Order the graphs, the DataTable, and the Sliders, then display them
layout = column(row(p1, row(bg_bot,bg_top)))


This is a pared down version of the script; for this to run, you need two jpg files in the same directory as the one you’re running the script from, one named “top.jpg” and the other named “bot.jpg”.

This is how I would write that:

top = p1.image_url(...)
bot = p1.image_url(...)

bg_top.js_link('value', top.glyph, 'global_alpha')
bg_bot.js_link('value', bot.glyph, 'global_alpha')

That’ll do it; thank you!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.