Creating a Scatter Plot with Bokeh in Python

  • Share this:

Code introduction


This function uses the Bokeh library to create a scatter plot, where x and y are the input coordinate data. The function first creates a ColumnDataSource to store the data, then creates a plot object, adds a scatter renderer, axes, and a title. Finally, it saves the generated graph as an HTML file.


Technology Stack : Bokeh library, ColumnDataSource, plot, scatter renderer, axes, title, HTML file

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
import numpy as np
import bokeh.plotting as bp
from bokeh.models import ColumnDataSource, LinearAxis, Title

def plot_scatter_data(x, y):
    # Create a ColumnDataSource
    data = ColumnDataSource(data=dict(x=x, y=y))

    # Create a new plot with a title and axis labels
    p = bp.figure(title="Scatter Plot", tools="pan,wheel_zoom,box_zoom,reset", axis_label_x="X-axis", axis_label_y="Y-axis")

    # Add a scatter renderer to the plot
    p.add_scatter(x='x', y='y', source=data, size=10, color='blue')

    # Add axis
    p.add_layout(LinearAxis(), 'below')
    p.add_layout(LinearAxis(), 'left')

    # Add a title to the plot
    p.add_layout(Title(text="Scatter Plot with Bokeh", align="center"))

    # Save the plot to an HTML file
    bp.save(p, filename="scatter_plot.html")

# Example usage
x = np.random.rand(50)
y = np.random.rand(50)
plot_scatter_data(x, y)