Bokeh Line Plot with Random Data

  • Share this:

Code introduction


This function generates a line plot with random data using the Bokeh library. It first generates random X and Y values, then creates a ColumnDataSource to store these data. Next, it creates a new plot with a title and axis labels, and adds a line plot with a diamond marker. Finally, it saves the plot as an HTML file.


Technology Stack : Bokeh, NumPy

Code Type : Function

Code Difficulty : Intermediate


                
                    
import numpy as np
import bokeh.plotting as plt
from bokeh.models import ColumnDataSource

def generate_random_plot(data_points=100):
    # Generate random x and y values
    x = np.random.random(data_points)
    y = np.random.random(data_points)

    # Create a ColumnDataSource to hold the data
    source = ColumnDataSource(data=dict(x=x, y=y))

    # Create a new plot with a title and axis labels
    p = plt.figure(title="Random Data Plot", tools="pan,wheel_zoom,box_zoom,reset")

    # Add a line renderer with a diamond marker
    p.line('x', 'y', source=source, line_color='blue', line_width=2, marker='diamond', marker_size=8)

    # Set the x and y axis labels
    p.xaxis.axis_label = 'X Axis'
    p.yaxis.axis_label = 'Y Axis'

    # Save the plot to a file
    plt.save(p, "random_data_plot.html")

    return p                
              
Tags: