Scientific Visualisations with Python

Visualizing Experimental Measurements Over Time

After generating the synthetic measurement data, we can explore how the measured physical quantities vary over time. In this example, we will use scatter plots to visualize temperature, pressure, and energy.

Unlike line plots, scatter plots display individual measurements without connecting them. This is particularly useful for experimental data because each point represents a separate observation, and measurements do not necessarily need to be regularly spaced in time.

Loading the Measurement Data

First, we load the measurement data from the CSV file using Pandas.

import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("../data/measurements.csv")

The read_csv() function loads the contents of the CSV file into a Pandas DataFrame. Each row represents one experimental measurement, while columns contain the corresponding variables, including time, temperature, pressure, and energy.

Creating Multiple Subplots

To compare the evolution of several physical quantities, we create a figure containing three vertically arranged subplots.

fig, axes = plt.subplots(3, 1, figsize=(11, 9), sharex=True)

The plt.subplots() function creates a figure and a set of axes for plotting.

The first argument specifies the number of rows, while the second specifies the number of columns. In this case, we create three rows and one column.

Sharing the time axis makes it easier to compare different physical quantities at corresponding time points.

Visualizing Temperature Over Time

The first subplot displays temperature as a function of time.

axes[0].scatter(
    df["time"],
    df["temperature"],
    color="red",
    s=8,
    alpha=0.4
)
axes[0].set_ylabel("Temperature [°C]")
axes[0].set_title("Temperature evolution")

The scatter() function creates a scatter plot using two columns from the DataFrame.

The first argument, df["time"] , defines the horizontal coordinates (x-axis), while the second argument, df["temperature"] , defines the vertical coordinates (y-axis).

Each point represents one temperature measurement recorded at a particular time.

Why Use Scatter Plots?

Scatter plots are particularly useful for visualizing experimental measurements because they preserve the original data.

In this example, we do not need to sort the measurements by time, divide the time range into intervals, or calculate average values.

Each point corresponds directly to one observation in the original dataset.

Connecting the points with lines could be misleading because the measurements are recorded at randomly distributed time points. A line would suggest a continuous relationship or trajectory between consecutive observations that may not actually exist.

Visualizing the Spatial Distribution of Temperature in 3D

In addition to examining how physical quantities change over time, we can visualize how temperature is distributed across three-dimensional space. A 3D scatter plot allows us to represent the spatial coordinates of individual measurements and use color to indicate their temperature values.

Selecting a Sample of Measurements

Since the dataset may contain a large number of observations, we select a random sample of 10,000 measurements to make the visualization easier to interpret.

sample = df.sample(10000, random_state=42)

The sample() function selects a random subset of rows from the DataFrame. The random_state parameter ensures that the same observations are selected each time the script is executed.

Creating a 3D Scatter Plot

Next, we create a three-dimensional plotting area using Matplotlib.

fig = plt.figure(figsize=(11, 8))
ax = fig.add_subplot(111, projection="3d")

The projection="3d" argument enables three-dimensional visualization, allowing us to plot measurements using their X, Y, and Z coordinates.

We then create the scatter plot:

scatter = ax.scatter(
    sample["x"],
    sample["y"],
    sample["z"],
    c=sample["temperature"],
    cmap="inferno",
    s=15,
    alpha=0.8
)

The X, Y, and Z columns define the spatial position of each measurement. The c parameter maps temperature values to colors, while cmap specifies the color scheme.

The s parameter controls marker size, and alpha controls transparency.

Adding a Colorbar and Axis Labels

To make the visualization easier to interpret, we add a colorbar and label the spatial axes.

fig.colorbar(
    scatter,
    ax=ax,
    label="Temperature [°C]",
    shrink=0.7
)
ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_zlabel("Z")
ax.set_title("3D Spatial Distribution of Temperature")
plt.tight_layout()
plt.show()

The colorbar indicates how colors correspond to temperature values. This makes it possible to identify regions with higher and lower temperatures directly from the plot.

Visualizing the Spatial Temperature Distribution Using Contour Plots

In addition to 3D scatter plots, we can visualize the spatial distribution of temperature using contour plots. This approach allows us to represent temperature variations across a two-dimensional plane using colors and contour lines.

Selecting a Spatial Region and Time Interval

First, we select measurements corresponding to a specific spatial region and time interval. In this example, we examine a slice around Z = 0 and time = 5.

z0 = 0
t0 = 5
subset = df[
    (df["z"].between(z0 - 0.6, z0 + 0.6)) &
    (df["time"].between(t0 - 0.6, t0 + 0.6))
]

The between() function selects rows where values fall within a specified range. This allows us to restrict the analysis to measurements close to the selected Z coordinate and time.

Creating a Regular Grid

To generate a contour plot, we first define a regular grid covering the spatial region of interest.

xi = np.linspace(-5, 5, 100)
yi = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(xi, yi)

The linspace() function generates evenly spaced coordinates between -5 and 5. The meshgrid() function combines these coordinates into two-dimensional arrays representing the X and Y positions of the grid points.

Interpolating Temperature Values

Since the original measurements are not necessarily located on a regular grid, we use interpolation to estimate temperature values at the grid points.

Z = griddata(
    (subset["x"], subset["y"]),
    subset["temperature"],
    (X, Y),
    method="linear"
)

The griddata() function from SciPy interpolates temperature values using the available experimental measurements.

The method="linear" parameter specifies linear interpolation, which estimates values between neighboring measurement points.

The resulting array Z contains the interpolated temperature values across the two-dimensional spatial grid.

Creating a Filled Contour Plot

Next, we visualize the interpolated temperature field using a filled contour plot.

fig, ax = plt.subplots(figsize=(10, 8))
contour = ax.contourf(
    X, Y, Z,
    levels=25,
    cmap="inferno"
)

The contourf() function creates filled contour regions. The levels parameter determines the number of contour levels, while cmap specifies the color map used to represent temperature values.

Adding Contour Lines and a Colorbar

To make temperature gradients easier to identify, we add contour lines on top of the filled plot.

ax.contour(
    X, Y, Z,
    levels=10,
    colors="white",
    linewidths=0.5,
    alpha=0.5
)
fig.colorbar(
    contour,
    ax=ax,
    label="Temperature [°C]"
)

The contour() function draws lines connecting locations with equal temperature values. These lines complement the filled color regions and make spatial temperature gradients easier to interpret.

The colorbar provides a reference for converting colors into actual temperature values.

Adding Labels and Displaying the Plot

Finally, we add axis labels and a title describing the selected spatial slice and time interval.

ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_title(
    f"Spatial Temperature Field | Z={z0}, Time={t0}"
)
ax.set_aspect("equal")
plt.tight_layout()
plt.show()

The set_aspect("equal") function ensures that the X and Y axes use the same scale, preserving the spatial proportions of the visualization.

The resulting contour plot provides a two-dimensional representation of the temperature field at a selected spatial location and time interval. Unlike a scatter plot, it uses interpolation to create a continuous visual representation of the measured temperature distribution.

Visualizing the Velocity Field Using Vector Plots

In addition to visualizing temperature distributions, we can examine how the fluid or measured system moves through space. A vector plot allows us to represent both the direction and magnitude of velocity at different spatial locations.

Selecting a Spatial Region and Time Interval

First, we select measurements corresponding to a specific spatial region and time interval. As in the previous example, we examine a slice around Z = 0 and time = 5.

z0 = 0
t0 = 5
subset = df[
    (df["z"].between(z0 - 0.6, z0 + 0.6)) &
    (df["time"].between(t0 - 0.6, t0 + 0.6))
]

The between() function selects measurements within the specified spatial and temporal ranges. This ensures that the velocity field represents observations from approximately the same spatial plane and time.

Creating a Regular Spatial Grid

Next, we define a regular grid over the region of interest.

xi = np.linspace(-5, 5, 25)
yi = np.linspace(-5, 5, 25)
X, Y = np.meshgrid(xi, yi)

The linspace() function generates evenly spaced coordinates between -5 and 5. The meshgrid() function combines these coordinates into two-dimensional arrays representing the positions where velocity vectors will be displayed.

In this example, we use 25 points along each axis to create a grid of 625 positions.

Interpolating Velocity Components

The original measurements are not necessarily located at the grid points. Therefore, we use interpolation to estimate the velocity components at each position.

U = griddata(
    (subset["x"], subset["y"]),
    subset["velocity_x"],
    (X, Y),
    method="linear"
)
V = griddata(
    (subset["x"], subset["y"]),
    subset["velocity_y"],
    (X, Y),
    method="linear"
)

The griddata() function interpolates the velocity components using the available experimental measurements.

The U array contains the interpolated velocity values in the X direction, while V contains the values in the Y direction.

The method="linear" parameter specifies linear interpolation between neighboring measurement points.

Calculating Velocity Magnitude

To represent not only the direction but also the magnitude of velocity, we calculate the speed at each grid point.

speed = np.sqrt(U**2 + V**2)

This value describes how fast the system is moving, independently of its direction.

Creating a Velocity Vector Plot

Next, we create the vector visualization using Matplotlib.

fig, ax = plt.subplots(figsize=(10, 8))
field = ax.quiver(
    X, Y, U, V, speed,
    cmap="viridis",
    scale=15,
    width=0.004
)

The quiver() function creates a vector plot.

The X and Y arrays define the positions of the vectors, while U and V determine their horizontal and vertical components.

The speed parameter maps velocity magnitude to colors, allowing us to distinguish regions with different flow speeds.

The cmap parameter specifies the color map, while scale controls the vector scaling and width determines arrow thickness.

Animation

In addition to static visualizations, we can use animations to explore how a physical quantity is distributed across different spatial slices. In this example, we animate temperature values along a selected spatial axis while keeping time fixed.

Preparing the Data

First, we load the spatial grid data and select measurements corresponding to a specific time.

df = pd.read_csv("../data/spatial_grid.csv")
t0 = 5
field_name = "temperature"
slice_axis = "x"
df = df[df["time"] == t0].copy()
n = 35
axis = np.linspace(-5, 5, n)
values = df[field_name].to_numpy().reshape((n, n, n))

The data is reshaped into a three-dimensional array representing the spatial temperature distribution. The variable slice_axis determines the direction in which the animation will move.

Defining the Animation

We use get_slice() to extract a two-dimensional slice from the three-dimensional temperature array. The update() function updates the displayed image for each animation frame.

The imshow() function displays the selected slice as a color-coded image, while FuncAnimation() generates the animation by repeatedly calling the update function.

animation = FuncAnimation(
    fig,
    update,
    frames=n,
    interval=150,
    blit=False,
    repeat=True
)

The frames parameter specifies the number of animation frames, while interval defines the delay between frames in milliseconds. The repeat=True option makes the animation loop continuously.

Finally, plt.show() displays the animation.