Random Data Plot Generation with Bokeh and Pandas

  • Share this:

Code introduction


This function uses the Bokeh library to create a chart displaying randomly generated data points. It retrieves data from a Pandas DataFrame and passes it to Bokeh's ColumnDataSource. Then, it creates a plot where data points are displayed as lines and circles, and a hover tool is added to display more information.


Technology Stack : Bokeh, Pandas, NumPy

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
import numpy as np
import pandas as pd
from bokeh.plotting import figure, show
from bokeh.layouts import gridplot
from bokeh.models import ColumnDataSource, HoverTool

def generate_random_plot(data, x_column, y_column, title="Random Plot"):
    # Create a DataFrame from the data
    df = pd.DataFrame(data)

    # Create a ColumnDataSource from the DataFrame
    source = ColumnDataSource(df)

    # Create a figure
    p = figure(title=title, tools="pan,wheel_zoom,box_zoom,reset")

    # Add a line renderer with a label and legend and bind the data
    p.line(x_column, y_column, source=source, legend_label="Line", color="blue")

    # Add a circle renderer with a label and legend and bind the data
    p.circle(x_column, y_column, source=source, legend_label="Circle", color="red", size=10)

    # Add a hover tool
    hover = HoverTool(tooltips=[
        ("index", "$index"),
        ("(x,y)", "($x, $y)"),
        ("value", "@y"),
    ])
    p.add_tools(hover)

    # Create a gridplot with the figure
    grid = gridplot(children=[p], ncols=1, plot_width=800, plot_height=400)

    # Display the gridplot
    show(grid)

# Sample data
data = {
    'x': np.random.rand(50),
    'y': np.random.rand(50)
}

# Call the function with the sample data
generate_random_plot(data, 'x', 'y')