Bokeh is a powerful Python library for interactive visualizations. You can create multiple plots within a single figure or layout to display various types of data. Here’s a step-by-step guide on how to plot multiple plots using Bokeh:
1. Install Bokeh
If you haven’t installed Bokeh yet, you can do so using pip:
pip install bokeh
2. Import Required Libraries
Import the necessary modules from Bokeh:
from bokeh.plotting import figure, show, output_file
from bokeh.layouts import column, row
3. Create Multiple Plots
You can create multiple plots by creating instances of the figure
class. Here’s an example of creating two plots:
# Create the first plot
plot1 = figure(title="Plot 1", x_axis_label='x', y_axis_label='y')
plot1.line([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], line_width=2, color='blue', legend_label="Line 1")
# Create the second plot
plot2 = figure(title="Plot 2", x_axis_label='x', y_axis_label='y', x_range=plot1.x_range, y_range=plot1.y_range)
plot2.scatter([1, 2, 3, 4, 5], [6, 2, 7, 4, 5], size=10, color='red', legend_label="Scatter 1")
4. Arrange Plots in a Layout
Use Bokeh’s row
or column
layout functions to arrange multiple plots. For example, you can arrange the two plots created above in a vertical column:
layout = column(plot1, plot2)
5. Output the Plots to an HTML File
Specify the output file where the plots will be saved, and display the plots:
# Specify the output file
output_file("multiple_plots.html")
# Show the plots
show(layout)
6. Complete Example Code
Here’s the complete code for creating and displaying multiple plots using Bokeh:
from bokeh.plotting import figure, show, output_file
from bokeh.layouts import column
# Create the first plot
plot1 = figure(title="Plot 1", x_axis_label='x', y_axis_label='y')
plot1.line([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], line_width=2, color='blue', legend_label="Line 1")
# Create the second plot
plot2 = figure(title="Plot 2", x_axis_label='x', y_axis_label='y', x_range=plot1.x_range, y_range=plot1.y_range)
plot2.scatter([1, 2, 3, 4, 5], [6, 2, 7, 4, 5], size=10, color='red', legend_label="Scatter 1")
# Arrange the plots in a column layout
layout = column(plot1, plot2)
# Specify the output file
output_file("multiple_plots.html")
# Show the plots
show(layout)
7. Additional Tips
- Customizing Layout: You can use the
row
function to place plots side by side or combinerow
andcolumn
for more complex layouts. - Interactive Widgets: You can add interactive widgets like sliders, dropdowns, or buttons to enhance your plots.
- Styling and Themes: Bokeh provides options to style your plots and apply themes to make them visually appealing.
This guide covers the basics of creating and arranging multiple plots using Bokeh in Python. Explore Bokeh’s extensive documentation for more advanced features and customizations.