How can Bokeh be used to draw random rectangles that have a specific alignment using Python?

Bokeh is a Python package for interactive data visualization. It renders plots using HTML and JavaScript, making it ideal for web-based dashboards and modern browsers.

Unlike Matplotlib and Seaborn which produce static plots, Bokeh creates interactive visualizations that respond to user interactions. Plots can be embedded in Flask or Django applications and rendered in Jupyter notebooks.

Installation

Install Bokeh using pip or conda ?

pip install bokeh

Or using Anaconda ?

conda install bokeh

Drawing Random Rectangles with Alignment

You can draw rectangles by specifying their center point, dimensions, and rotation angle using the rect() function. The angle parameter controls the alignment/rotation.

Example

from math import pi
from bokeh.plotting import figure, output_file, show

# Create output file
output_file('rectangles_random.html')

# Create figure
p = figure(width=400, height=400, title="Random Rectangles with Alignment")

# Draw rectangles with specific alignment (rotated by pi/3 radians)
p.rect(x=[1, 3, 5, 7], y=[1, 3, 5, 7], 
       width=0.8, height=0.6, 
       color="#CAB2D6", 
       angle=pi/3, 
       alpha=0.7)

# Display the plot
show(p)

Parameters Explained

Parameter Description
x, y Center coordinates of rectangles
width, height Dimensions of rectangles
angle Rotation angle in radians (controls alignment)
color Fill color of rectangles
alpha Transparency (0-1)

Multiple Alignment Examples

from math import pi
from bokeh.plotting import figure, show
from bokeh.layouts import row

# Create three figures with different alignments
p1 = figure(width=300, height=300, title="No Rotation (0°)")
p1.rect(x=[2, 4], y=[2, 4], width=1, height=0.5, color="red")

p2 = figure(width=300, height=300, title="45° Rotation")
p2.rect(x=[2, 4], y=[2, 4], width=1, height=0.5, color="blue", angle=pi/4)

p3 = figure(width=300, height=300, title="60° Rotation")
p3.rect(x=[2, 4], y=[2, 4], width=1, height=0.5, color="green", angle=pi/3)

# Display all plots in a row
show(row(p1, p2, p3))

Conclusion

Bokeh's rect() function allows you to create rectangles with specific alignments using the angle parameter. This enables creating visually appealing patterns and layouts in your interactive visualizations.

Updated on: 2026-03-25T15:28:41+05:30

270 Views

Advertisements