Scientific Visualisations with Python

Creating Interactive Scatter Plots Using Bokeh

In addition to static visualizations created with Matplotlib and Seaborn, we can use Bokeh to create interactive plots that allow users to explore experimental measurements directly.

In this example, we create a scatter plot showing the relationship between temperature and pressure, with different colors representing experimental groups.

Loading and Preparing the Data

First, we load the measurement data and select a random sample of 3,000 observations to improve visualization performance.

import pandas as pd
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure, show
from bokeh.transform import factor_cmap
from bokeh.palettes import Category10
df = pd.read_csv("../data/measurements.csv")
df = df.sample(3000, random_state=42)

The sample() function selects a subset of measurements, while random_state ensures reproducibility.

Next, we convert the DataFrame into a Bokeh data source.

source = ColumnDataSource(df)
groups = ["Control", "Experiment A", "Experiment B"]

The `ColumnDataSource` object provides data in a format that Bokeh can use for interactive visualizations.

Creating an Interactive Figure

Next, we create the plotting area and configure its interactive tools.

p = figure(
    title="Temperature vs Pressure",
    width=850,
    height=550,
    tools="pan,wheel_zoom,box_zoom,reset,save",
    tooltips=[
        ("Group", "@group"),
        ("Temperature", "@temperature{0.0}"),
        ("Pressure", "@pressure{0.0}")
    ]
)

The figure() function creates the plotting area.

The width and height parameters define its dimensions, while tools specifies the available interactions:

• `pan` allows users to move around the plot.
• `wheel_zoom` enables zooming with the mouse wheel.
• `box_zoom` allows selecting a region to zoom in.
• `reset` restores the original view.
• `save` allows exporting the plot.

The tooltips parameter defines information displayed when hovering over individual measurements.

Adding Scatter Points and Colors

We use the scatter() function to display the measurements.

p.scatter(
    "temperature",
    "pressure",
    source=source,
    size=8,
    alpha=0.6,
    color=factor_cmap("group", Category10[3], groups),
    legend_field="group"
)

The first two arguments define the X and Y coordinates using temperature and pressure.

The factor_cmap() function assigns different colors to experimental groups. The Category10[3] palette provides three distinct colors.

The legend_field parameter creates a legend based on group names.

Configuring the Legend and Axis Labels

Finally, we configure the legend and axis labels.

p.legend.click_policy = "hide"
p.xaxis.axis_label = "Temperature"
p.yaxis.axis_label = "Pressure"

The click_policy="hide" option allows users to click legend entries to hide or display individual experimental groups.

Displaying the Interactive Plot

We display the completed visualization using Bokeh.

show(p)

The resulting plot allows users to explore the relationship between temperature and pressure interactively, inspect individual measurements, zoom into selected regions, and compare experimental groups.

Visualizing Temperature Changes Over Time Using Bokeh

In this example, we use Bokeh to create an interactive line plot showing how average temperature changes over time across different experimental groups.

Preparing and Aggregating the Data

First, we divide the time range into 40 intervals and calculate the average time and temperature for each group.

df["time_bin"] = pd.cut(df["time"], bins=40)
summary = (
    df.groupby(["group", "time_bin"], observed=True)
    .agg(time=("time", "mean"), temperature=("temperature", "mean"))
    .reset_index()
)

The pd.cut() function divides time into intervals, while groupby() and agg() calculate average values for each group and interval.

Creating the Interactive Line Plot

Next, we create the Bokeh figure and define colors for the experimental groups.

p = figure(
    title="Temperature Changes Over Time",
    width=900,
    height=500,
    tools="pan,wheel_zoom,box_zoom,reset,save"
)
colors = {
    "Control": "navy",
    "Experiment A": "orange",
    "Experiment B": "green"
}

We then plot a separate line for each group.

for group, data in summary.groupby("group"):
    p.line(
        data["time"],
        data["temperature"],
        line_width=2,
        color=colors[group],
        legend_label=group
    )

Each line represents the average temperature evolution for one experimental group.

Configuring and Displaying the Plot

Finally, we configure the legend and axis labels.

p.legend.click_policy = "hide"
p.xaxis.axis_label = "Time"
p.yaxis.axis_label = "Temperature"
show(p)

Creating Multiple Interactive Scatter Plots with Bokeh

Bokeh allows us to create multiple interactive plots and display them side by side. This makes it easier to compare relationships between different variables while working with the same dataset.

In this example, we create two scatter plots: one showing the relationship between temperature and pressure, and the other showing the relationship between temperature and energy.

Preparing the Data

First, we load the dataset using read_csv() and select a random sample of 1500 rows. The random_state parameter ensures that the same sample is selected each time the code is executed.

df = pd.read_csv("../data/measurements.csv")
df = df.sample(1500, random_state=42)

source = ColumnDataSource(df)

The ColumnDataSource() object provides a shared data source for both plots. This allows the plots to use the same dataset and supports coordinated interactions such as selecting data points.

Defining Interactive Tools

The available interactive tools are specified using a string:

tools = "pan,wheel_zoom,box_select,lasso_select,reset"

These tools allow users to:
• pan – move around the plot.
• wheel_zoom – zoom in and out using the mouse wheel.
• box_select – select points inside a rectangular area.
• lasso_select – select points by drawing a freeform shape.
• reset – restore the original plot view.

The same tools are enabled for both figures.

Creating the Scatter Plots

The first figure displays temperature against pressure:

p1 = figure(
    title="Temperature vs Pressure",
    width=450,
    height=450,
    tools=tools
)
p1.scatter(
    "temperature",
    "pressure",
    source=source,
    size=7,
    alpha=0.5
)

The second figure displays temperature against energy:

p2 = figure(
    title="Temperature vs Energy",
    width=450,
    height=450,
    tools=tools
)
p2.scatter(
    "temperature",
    "energy",
    source=source,
    size=7,
    alpha=0.5
)

Both plots use the same ColumnDataSource() object. The size parameter controls the marker size, while alpha determines its transparency. A value of 0.5 makes the points partially transparent, which helps when many points overlap.

Setting Axis Labels and Arranging the Plots

Axis labels are assigned separately for each figure:

p1.xaxis.axis_label = "Temperature"
p1.yaxis.axis_label = "Pressure"
p2.xaxis.axis_label = "Temperature"
p2.yaxis.axis_label = "Energy"

Finally, the row() function arranges the two figures horizontally, and show() displays the resulting layout:

show(row(p1, p2))

Bokeh allows us to create interactive plots with dropdown menus that filter data dynamically. In this example, we display temperature against pressure and allow users to filter observations by experimental group.

Preparing the Data

First, we load the dataset and create two data sources:

df = pd.read_csv("../data/measurements.csv")
source = ColumnDataSource(df[["temperature", "pressure", "group"]])
view = ColumnDataSource(df[["temperature", "pressure"]])

The source object stores the original data, while view contains only the values displayed in the plot.

Creating the Dropdown Menu

We use Select() to create a dropdown menu:

select = Select(
    title="Experimental group",
    value="All",
    options=["All", "Control", "Experiment A", "Experiment B"]
)

Users can select a specific experimental group or "All" to display every observation.

Creating the Scatter Plot

Next, we create a scatter plot:

p = figure(
    title="Filtered Experimental Measurements",
    width=850,
    height=500,
    tools="pan,wheel_zoom,box_zoom,reset,save"
)
p.scatter(
    "temperature",
    "pressure",
    source=view,
    size=7,
    alpha=0.5
)

The plot uses view as its data source, allowing the displayed points to be updated dynamically.

Defining the Interactive Callback

We use CustomJS() to filter the data whenever the dropdown selection changes:

The callback checks each observation and adds it to the filtered dataset if it belongs to the selected group. Choosing "All" displays every observation.

We connect the callback to the dropdown menu:

select.js_on_change("value", callback)

The callback executes automatically whenever the selected value changes.

Displaying the Layout

Finally, we set the axis labels and display the dropdown menu above the plot:

p.xaxis.axis_label = "Temperature"
p.yaxis.axis_label = "Pressure"
show(column(select, p))

The column() function arranges the elements vertically, while show() displays the interactive visualization.

Summary

In this example, we used:
• ColumnDataSource() – stores the original and filtered data.
• Select() – creates the dropdown menu.
• CustomJS() – defines the filtering logic in JavaScript.
• js_on_change() – triggers filtering when the selection changes.
• column() – arranges the layout.