October 13, 2024

Plotting Rays on a Graph Using Bokeh in Python

Bokeh is a powerful Python library for interactive data visualization. It allows you to create a wide range of plots, including lines, scatter plots, and custom shapes like rays. This guide demonstrates how to plot rays on a graph using Bokeh.

1. Installation

If you don’t have Bokeh installed, you can install it using pip:

pip install bokeh
    

2. Basic Example

To plot rays on a graph using Bokeh, you will use the line glyph to represent the rays. Here’s a simple example:

from bokeh.plotting import figure, show
from bokeh.io import output_file

# Create an output file
output_file('rays_plot.html')

# Create a new plot with title and labels
p = figure(title="Rays Plot", x_axis_label='X', y_axis_label='Y')

# Define the origin and direction for the rays
origin_x = [0, 0, 0]
origin_y = [0, 0, 0]
ray_lengths = [10, 15, 20]
ray_angles = [0, 45, 90]

# Convert angles to radians
import numpy as np
ray_angles_rad = np.radians(ray_angles)

# Compute the end points of the rays
end_x = [o + l * np.cos(a) for o, l, a in zip(origin_x, ray_lengths, ray_angles_rad)]
end_y = [o + l * np.sin(a) for o, l, a in zip(origin_y, ray_lengths, ray_angles_rad)]

# Plot the rays
p.line(x=origin_x + end_x, y=origin_y + end_y, line_color="blue")

# Show the plot
show(p)
    

3. Explanation

In this example:

  • Setup: The output_file function specifies the output file where the plot will be saved.
  • Plot Creation: A new Bokeh figure is created with titles and labels for the axes.
  • Ray Parameters: Origin points, ray lengths, and angles are defined. Angles are converted to radians for trigonometric calculations.
  • End Points Calculation: The end points of the rays are calculated using trigonometric functions cos and sin.
  • Plotting Rays: The line glyph is used to draw the rays from the origin to the computed end points.
  • Display: The show function renders the plot in the specified output file.

4. Conclusion

Using Bokeh to plot rays on a graph involves setting up the plot, defining ray parameters, and calculating the end points based on trigonometric functions. This approach can be adapted for more complex visualizations and interactive plots as needed.