基于组件选择实现Bokeh图表中数据系列的显示/隐藏
Got it, let's put together a fully functional interactive Bokeh plot in Jupyter Notebook where you can toggle data series on and off using a checkbox button group. Here's a complete implementation that fills in the gaps in your code and adds the required interactivity:
Complete Working Code
from bokeh.io import output_notebook, show from bokeh.plotting import figure from bokeh.palettes import Dark2_5 as palette from bokeh.layouts import row from bokeh.models.widgets import CheckboxButtonGroup from bokeh.models import CustomJS import numpy as np output_notebook() # Generate sample data (replace with your actual data) x = np.arange(20) num_series = len(palette) # Create 5 distinct y series (adjust logic to match your data) y_series = [np.sin(x/2 + i*np.pi/3) + np.random.randn(20)*0.1 for i in range(num_series)] series_names = [f"Series {i+1}" for i in range(num_series)] # Initialize the plot p = figure(plot_width=800, plot_height=400, title="My Interactive Line Plot") # Add all data lines to the plot and store references lines = [] for y, color, name in zip(y_series, palette, series_names): # Add line with unique name and legend label line = p.line(x, y, line_width=2, color=color, legend_label=name, name=name) lines.append(line) # Create the checkbox button group (all series active by default) checkbox_group = CheckboxButtonGroup( labels=series_names, active=list(range(num_series)) # Default: show all series ) # JavaScript callback to toggle line visibility callback = CustomJS(args=dict(lines=lines, checkbox=checkbox_group), code=""" // Get the indices of currently active checkboxes const activeIndices = checkbox.active; // Update visibility for each line lines.forEach((line, index) => { line.visible = activeIndices.includes(index); }); """) # Link the checkbox group to the callback checkbox_group.js_on_change('active', callback) # Arrange the checkbox and plot side by side layout = row(checkbox_group, p) # Show the interactive plot in Jupyter show(layout)
Key Details Explained
- Data Setup: I used sine waves with small random noise for sample data, but you can replace
y_serieswith your actual dataset. - Line Tracking: We store references to each line we add to the plot—this lets us modify their visibility later.
- Checkbox Control: The
CheckboxButtonGroupstarts with all series visible (you can change theactiveparameter to default to hiding some series). - CustomJS Callback: This lightweight JavaScript function runs directly in your browser (no Bokeh Server needed) to update line visibility whenever the checkbox selection changes. It checks if a line's index is in the
activearray and setsvisibleaccordingly.
How It Works
- Run the code in your Jupyter Notebook—you'll see a plot with all data series and a group of checkboxes on the left.
- Click any checkbox to toggle the corresponding series on or off. The plot updates instantly!
内容的提问来源于stack exchange,提问作者nickos556
相关产品推荐
相关产品推荐

