Create a plot with Multiple Glyphs using Python Bokeh

Create a plot with Multiple Glyphs using Python Bokeh

Creating a plot with multiple glyphs in Bokeh, a Python interactive visualization library, allows for more detailed and complex visualizations. Bokeh's plotting API supports a wide range of glyphs (basic visual markers) like lines, circles, bars, and more. Here's how to create a Bokeh plot with multiple glyphs:

Step 1: Install Bokeh

If you haven't installed Bokeh, you can do so using pip:

pip install bokeh 

Step 2: Import Bokeh Modules

Import the necessary modules from Bokeh:

from bokeh.plotting import figure, show, output_file 

Step 3: Prepare Data

Prepare the data that you will plot. For this example, let's create simple data for demonstration:

x = [1, 2, 3, 4, 5] y1 = [6, 7, 2, 4, 5] y2 = [2, 3, 4, 5, 6] y3 = [4, 5, 5, 7, 2] 

Step 4: Create a Figure

Create a figure object which will serve as the canvas for your plot:

p = figure(title="Multiple Glyphs Example", x_axis_label='X', y_axis_label='Y') 

Step 5: Add Multiple Glyphs

Add different types of glyphs to the figure. For instance, lines, circles, and squares:

# Line glyph p.line(x, y1, legend_label="Line", line_width=2) # Circle glyph p.circle(x, y2, legend_label="Circle", size=10, color="red", alpha=0.5) # Square glyph p.square(x, y3, legend_label="Square", size=10, color="green", alpha=0.5) 

Step 6: Output and Show the Plot

Finally, output and show your plot. You can output to a file or display inline in a Jupyter notebook.

# Output to static HTML file output_file("multiple_glyphs.html") # Show the result show(p) 

Complete Example

Here's the complete script:

from bokeh.plotting import figure, show, output_file # Prepare data x = [1, 2, 3, 4, 5] y1 = [6, 7, 2, 4, 5] y2 = [2, 3, 4, 5, 6] y3 = [4, 5, 5, 7, 2] # Create a figure p = figure(title="Multiple Glyphs Example", x_axis_label='X', y_axis_label='Y') # Add glyphs p.line(x, y1, legend_label="Line", line_width=2) p.circle(x, y2, legend_label="Circle", size=10, color="red", alpha=0.5) p.square(x, y3, legend_label="Square", size=10, color="green", alpha=0.5) # Output to static HTML file output_file("multiple_glyphs.html") # Show the result show(p) 

This script generates a plot with three different glyphs (line, circle, and square), each representing a different set of y-values for the same x-values. The plot is saved to an HTML file named multiple_glyphs.html.

Customization

You can further customize the plot by modifying glyph properties, adding tools, changing themes, and more. Bokeh's flexibility allows for a high degree of customization to suit your data visualization needs.


More Tags

talkback c#-4.0 javafx-2 data-access elm zebra-printers local-files go-map windows-authentication alt

More Programming Guides

Other Guides

More Programming Examples