Python Bokeh - Plotting Patches on a Graph

Python Bokeh - Plotting Patches on a Graph

In Bokeh, a powerful interactive visualization library in Python, you can use the patches method to plot multiple polygonal shapes, or patches, on a graph. This feature is particularly useful for visualizing complex datasets that can be represented as a collection of polygons, such as geographical regions on a map or irregularly shaped data clusters.

Here's a basic example to demonstrate how to plot patches on a graph using Bokeh:

Step 1: Install Bokeh

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

pip install bokeh 

Step 2: Create a Bokeh Plot with Patches

from bokeh.plotting import figure, show, output_file from bokeh.models import ColumnDataSource # Example data: multiple patches xs = [[1, 1, 2, 2], [2, 2, 4], [2, 2, 3, 3]] ys = [[2, 5, 5, 2], [3, 5, 5], [2, 3, 3, 2]] # Optional: additional data for each patch (e.g., colors) colors = ["blue", "green", "red"] # Create a ColumnDataSource source = ColumnDataSource(data=dict(xs=xs, ys=ys, colors=colors)) # Create a figure p = figure(title="Bokeh Patches Example", x_axis_label='x', y_axis_label='y') # Add patches to the figure p.patches('xs', 'ys', source=source, fill_color='colors', line_color="white") # Output to file (optional) output_file("patches.html") # Show the plot show(p) 

In this example:

  • We define xs and ys as lists of lists, where each inner list represents the x and y coordinates of the vertices of a patch.
  • An optional colors list is used to specify the fill color for each patch.
  • A ColumnDataSource is created to store the data.
  • The patches method is used on the figure p to plot the patches. The fill_color attribute is set to use the color data from the source.
  • Finally, show(p) displays the plot.

When you run this script, it will generate a plot with three patches, each colored differently.

Customization

You can customize the patches and the plot in various ways:

  • Line Properties: Customize the lines around the patches using attributes like line_color, line_width, and line_alpha.
  • Fill Properties: Change the fill properties with fill_alpha and fill_pattern.
  • Interactive Tools: Bokeh supports various interactive tools and widgets that can be added to enhance the interactivity of the plot.

Bokeh's ability to handle interactive and complex visualizations makes it a valuable tool for data analysis and presentation, especially when dealing with intricate datasets.


More Tags

elasticsearch-plugin file-not-found r-rownames hbm2ddl sqldataadapter cordova element collation venn-diagram hive

More Programming Guides

Other Guides

More Programming Examples