Dropdown Menu to change between holoviews Images in bokeh

I have code that produces multiple holoviews images and I want to display one at a time and be able to change between them using a DropDown menu. I looked around but do not find a solution for this.
ChatGPT has given me code that does what I want for geoviews figures, but can not reproduce it for my images.

#!/usr/bin/env python3

# plot interactive maps of data 

import numpy as np
import sys
import os
from astropy.time import Time

import geoviews as gv
from geoviews import opts as gvopts
import holoviews as hv
from bokeh.io import curdoc
from cartopy import crs
from holoviews.operation.datashader import regrid

from read_nc import read_dir_nc
from outfile import outfile
from merge_data import merge_data
from filter_invalid import filter_invalid


def command_parser(argv):

    # defaults
    data_path = "Testdata/*.nc"
    cnfg_path = "Testdata/config.json"

    usage = "usage: %prog [options]"
    
    from optparse import OptionParser
    
    parser = OptionParser(usage=usage)
    
    parser.add_option("-d", "--dpath",
                      action="store",
                      type="string",
                      dest="dpath",
                      default=data_path,
                      help="Path of netCDF files to be read, default: %default")

    parser.add_option("-c", "--config",
                      action="store",
                      type="string",
                      dest="cpath",
                      default=cnfg_path,
                      help="Path of config file to be read, default: %default")

    # args contains all non-option arguments
    (cdata, args) = parser.parse_args()
        
    return cdata, args


def merc_trans(lon, lat):
    """
    transform lat, lon to mercator coordinates
    """
    from pyproj import Transformer
    
    wgs84 = "epsg:4326"
    wgs84_pseudo_merc = "epsg:3857"

    # always_xy -> makes sure that output is (lon,lat)
    transformer = Transformer.from_crs(crs_from=wgs84, crs_to=wgs84_pseudo_merc, always_xy=True) 
    
    mlon, mlat = transformer.transform(xx=lon, yy=lat)

    return mlon, mlat


def prep_plot_data(data, cnfg):

    plotdata = dict()

    for file in cnfg.keys():

        plotdata[file] = dict()
        
        for variable in cnfg[file].keys():

            var = data[file]['variables']

            if variable not in var.keys():
                raise ValueError(f"The file {file} does not contain a variable called {variable}.")
            
            val = var[variable]
            val *= cnfg[file][variable]['scale']

            lat = var[cnfg[file][variable]['latvar']]
            lon = var[cnfg[file][variable]['lonvar']]

            if cnfg[file][variable]['numvar'] in var:
                N = var[cnfg[file][variable]['numvar']]
            else:
                N = np.ones_like(val)
            
            plotdata[file][variable] = dict()
            
            plotdata[file][variable]['lat'] = lat
            plotdata[file][variable]['lon'] = lon
            plotdata[file][variable]['N'] = N
            
            plotdata[file][variable]['value'] = val

    return plotdata


def geoviews_map_grid(plotdata, cnfg):

    #gv.extension('bokeh')
    

    curdoc().title = 'bokeh application'  # sets title of the bokeh document

    from get_cpt import get_cmap
    from holoviews.operation.datashader import regrid, rasterize, datashade
    from geoviews.operation.regrid import weighted_regrid

    figure_dict = dict()
    
    for file in plotdata.keys():
        figure_dict[file] = dict()
        for var in plotdata[file].keys():

            config = cnfg[file][var]
            
            val = plotdata[file][var]['value']
            lat = plotdata[file][var]['lat']
            lon = plotdata[file][var]['lon']
            N = plotdata[file][var]['N']

            # remove values with to low number of input data
            val = np.where(N<config['nmin'], np.nan, val)

            # statistics
            val_mean = np.nanmean(val)
            val_std = np.nanstd(val)

            # ranges
            vmean = np.floor(val_mean/5)*5.

            # auto range
            dv = config['dv']
            vmin = val_mean - dv
            vmax = val_mean + dv
            # specific range
            if config['zval'][0] != None:
                vmin = config['zval'][0]
            if config['zval'][1] != None:
                vmax = config['zval'][1]

            # apply limits
            val = np.clip(val, vmin, vmax)

            # background
            if config['tiles']:
                height = 800
                width  = 1000

                # offline tiles | still needs comand option for path
                tiles_dir = 'http://localhost:8000/tiles/GoogleTiles/{X}/{Y}/{Z}.png'
                tiles = gv.WMTS(tiles_dir).opts(global_extent=True, max_zoom=6)

                # need to limit lat range for tiles projection - exclude poles
                world_lon1, world_lat1 = merc_trans(config['xmin'], np.max([config['ymin'], -80.]))
                world_lon2, world_lat2 = merc_trans(config['xmax'], np.min([config['ymax'], 80.]))

                xlim = (world_lon1, world_lon2)
                ylim = (world_lat1, world_lat2)
                projection = crs.Mercator.GOOGLE
                bg_fig = tiles.opts(width=width, height=height,
                                    xlim=xlim, ylim=ylim)
                
            else:
                height = 800
                width  = 1000
                
                xlim = (config['xmin'], config['xmax'])
                ylim = (config['ymin'], config['ymax'])
                projection = crs.PlateCarree()

            gvopts.defaults(gvopts.Image(width=width, height=height,
                                         xlim=xlim, ylim=ylim))

            # data
            ds = gv.Dataset((lon, lat, val),
                            ['Longitude', 'Latitude'], var)
    
            hv.config.image_rtol = 0.01 # tolerance for lat/lon data
            # dynamic could be for time
            image = ds.to(gv.Image, ['Longitude', 'Latitude'])#, dynamic=True)

            # read color map from file
            cmap_file = './' + config['cmap'] + '.cpt'
            if os.path.exists(cmap_file):
                cmap = get_cmap(cmap_file)
            else:
                cmap = config['cmap']

            image.opts(colorbar=True,
                       clabel=var+' ('+config['unit']+')',
                       cmap=cmap,
                       alpha=0.55,
                       colorbar_opts={'scale_alpha':0.55},
                       xlabel='Länge',
                       ylabel='Breite',
                       projection=projection,
                       title=config['title'])

            dyn_coast = gv.operation.resample_geometry(
                gv.feature.coastline.geoms('10m').opts(color='black'))
            dyn_borders = gv.operation.resample_geometry(
                gv.feature.borders.geoms('10m').opts(color='black'))
            if config['tiles']:
                fig = bg_fig * regrid(image) * dyn_coast
            else:
                fig = regrid(image) * dyn_coast * dyn_borders

            figure_dict[file][var] = fig
                
    return figure_dict


def render_images(figures, cnfg):

    images = dict()

    for file in cnfg.keys():
        for var in cnfg[file].keys():
            dd_name = cnfg[file][var]['dd_name']
            images[dd_name] = figures[file][var]

    print(images.keys())
    
    fig = images["CO2 total columns"]
    #fig = images['Nitrogendioxide']
    #fig = images['CH4 total column']
    
    renderer = gv.renderer('bokeh')
    hv.renderer('bokeh').server_doc(fig)])
    
    return



# read & interpret command line
opts, _ = command_parser(sys.argv)
print("Input data path: ", opts.dpath)
print("Input config path: ", opts.cpath)

data, cnfg = read_dir_nc(opts.dpath, opts.cpath)

plotdata = prep_plot_data(data, cnfg)

figures = geoviews_map_grid(plotdata, cnfg)
print(figures.keys())

render_images(figures, cnfg)

This code is capable of producing the images that I want, but can’t change them using a DropDown menu. Does anyone have experience using bokeh?

ChatGPT sugested this:

import numpy as np
from bokeh.io import output_file, show
from bokeh.models import ColumnDataSource, Select, CustomJS, ColorBar, LinearColorMapper
from bokeh.layouts import column
from bokeh.plotting import figure
from bokeh.transform import linear_cmap
from bokeh.palettes import Viridis256

# Function to convert latitude and longitude to Web Mercator format
def wgs84_to_web_mercator(lat, lon):
    k = 6378137
    x = lon * (k * np.pi/180.0)
    y = np.log(np.tan((90 + lat) * np.pi/360.0)) * k
    return (x, y)

# Create the dataset dictionary
images = {}

# Create the first dataset as a ColumnDataSource
data1 = {
    'latitude': np.random.uniform(low=37.0, high=37.9, size=100),
    'longitude': np.random.uniform(low=-122.5, high=-121.5, size=100),
    'value': np.random.uniform(low=0, high=100, size=100)
}
data1['x'], data1['y'] = wgs84_to_web_mercator(data1['latitude'], data1['longitude'])
source1 = ColumnDataSource(data1)
images["Geographical Dataset 1"] = source1

# Create the second dataset as a ColumnDataSource
data2 = {
    'latitude': np.random.uniform(low=35.0, high=36.0, size=100),
    'longitude': np.random.uniform(low=-123.5, high=-122.5, size=100),
    'value': np.random.uniform(low=0, high=100, size=100)
}
data2['x'], data2['y'] = wgs84_to_web_mercator(data2['latitude'], data2['longitude'])
source2 = ColumnDataSource(data2)
images["Geographical Dataset 2"] = source2

# Calculate median and standard deviation for dataset 1
median1 = np.median(data1['value'])
std1 = np.std(data1['value'])
low1 = median1 - std1
high1 = median1 + std1

# Calculate median and standard deviation for dataset 2
median2 = np.median(data2['value'])
std2 = np.std(data2['value'])
low2 = median2 - std2
high2 = median2 + std2

# Create color mappers
color_mapper1 = LinearColorMapper(palette=Viridis256, low=low1, high=high1)
color_mapper2 = LinearColorMapper(palette=Viridis256, low=low2, high=high2)

# Create the first figure
p1 = figure(x_axis_type="mercator", y_axis_type="mercator", title="Geographical Dataset 1")
p1.circle(x='x', y='y', size=10, fill_color=linear_cmap('value', Viridis256, low1, high1), fill_alpha=0.8, source=source1)
color_bar1 = ColorBar(color_mapper=color_mapper1, location=(0, 0))
p1.add_layout(color_bar1, 'right')

# Create the second figure
p2 = figure(x_axis_type="mercator", y_axis_type="mercator", title="Geographical Dataset 2")
p2.circle(x='x', y='y', size=10, fill_color=linear_cmap('value', Viridis256, low2, high2), fill_alpha=0.8, source=source2)
color_bar2 = ColorBar(color_mapper=color_mapper2, location=(0, 0))
p2.add_layout(color_bar2, 'right')

# Hide the second plot initially
p2.visible = False

# Create a Select widget
select = Select(title="Select Plot:", value="Geographical Dataset 1", options=["Geographical Dataset 1", "Geographical Dataset 2"])

# Define a CustomJS callback to switch plots
callback = CustomJS(args=dict(p1=p1, p2=p2), code="""
    if (cb_obj.value == "Geographical Dataset 1") {
        p1.visible = true;
        p2.visible = false;
    } else {
        p1.visible = false;
        p2.visible = true;
    }
""")
select.js_on_change('value', callback)

# Combine the select widget and plots into a layout
layout = column(select, p1, p2)

# Save the plot to an HTML file and show it
output_file("geographical_datasets_with_dictionary_data.html")
show(layout)

New contributor

user24681547 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật