Physics Data Analysis in Python: A Beginner Workflow for Units, Fits, Uncertainty, and Plots
Pythondata analysisphysics labscurve fittinguncertainty analysisresearch skills

Physics Data Analysis in Python: A Beginner Workflow for Units, Fits, Uncertainty, and Plots

PPhysics Direct Editorial Team
2026-12-01
8 min read

A reproducible Python workflow for physics data: import measurements, preserve units, plot uncertainty, fit models, inspect residuals, and document results.

Good physics data analysis is more than drawing a best-fit line. This reusable Python workflow shows how to import measurements, preserve units, visualize patterns, fit models, estimate uncertainty, and document assumptions so that your results can be checked and reused.

Overview

A physics dataset usually contains three connected parts: measured quantities, a model that describes the expected relationship, and uncertainty associated with the measurements or the fitting process. Python can handle all three, but only if the workflow is organized carefully.

A practical sequence is:

  1. Define the physical question and model before inspecting the fit.
  2. Record what each column means, including units and uncertainty.
  3. Import the data without silently changing values or precision.
  4. Check ranges, missing values, repeated measurements, and obvious outliers.
  5. Convert quantities to a consistent unit system before calculating or fitting.
  6. Plot the raw data with meaningful axis labels and error bars.
  7. Fit the simplest defensible model.
  8. Compare fitted parameters with physical expectations and residuals.
  9. Save the code, input data, assumptions, and output figures together.

This approach applies to an introductory mechanics lab, an electromagnetism experiment, a materials measurement, or a small research project. For background on presenting uncertainty and discussion sections, see the physics lab report guide. If your measurements come from a phone or other embedded sensor, the smartphone physics experiments guide provides useful context about calibration and sampling.

A maintainable Python structure

Keep data preparation, analysis, and presentation separate. A small project can use this structure:

project/
  data/raw_measurements.csv
  notebooks/analysis.ipynb
  src/analysis.py
  figures/
  README.md
  requirements.txt

The raw file should remain unchanged. If you remove a row, convert a unit, or correct a transcription error, do it in code and explain the decision in the README or report. This makes the result reproducible instead of dependent on an undocumented spreadsheet edit.

Checklist by scenario

Scenario 1: Importing and checking measurements

Start with a table whose column names identify both the quantity and, preferably, its unit. For example: time_s, distance_m, and distance_unc_m. Avoid ambiguous headings such as x or value.

import pandas as pd
import numpy as np

raw = pd.read_csv("data/raw_measurements.csv")
print(raw.head())
print(raw.dtypes)
print(raw.isna().sum())
print(raw.describe())

Before fitting, check whether numerical columns were imported as numbers rather than text. Confirm that decimal separators, missing-value markers, and repeated measurements have been interpreted correctly. Do not delete an unusual point merely because it makes the graph look less tidy; first investigate whether it reflects a recording error, an instrument limit, or real behavior.

Scenario 2: Preserving units

Unit mistakes can produce a visually convincing but physically meaningless result. Convert measurements to a consistent system before calculating slopes, powers, or fitted parameters. A simple approach is to make conversion explicit:

# Example: convert centimetres to metres
raw["distance_m"] = raw["distance_cm"] / 100.0

For larger projects, a units package such as Pint can make conversions more visible and help catch incompatible operations. Even when you do not use a package, write the conversion in the analysis and record the original unit in the data dictionary. Dimensional analysis is an effective independent check; the guide to units and scaling laws explains how to use it.

Scenario 3: Plotting experimental data

A first plot should show the measurements before a model is applied. Include uncertainty bars when they are available, and label axes with quantity and unit.

import matplotlib.pyplot as plt

x = raw["time_s"].to_numpy()
y = raw["distance_m"].to_numpy()
y_unc = raw["distance_unc_m"].to_numpy()

fig, ax = plt.subplots()
ax.errorbar(x, y, yerr=y_unc, fmt="o", capsize=3, label="measurement")
ax.set_xlabel("Time (s)")
ax.set_ylabel("Distance (m)")
ax.set_title("Distance as a function of time")
ax.grid(True, alpha=0.3)
ax.legend()
fig.tight_layout()
fig.savefig("figures/distance_vs_time.png", dpi=200)
plt.show()

Use a scatter plot for discrete measurements rather than connecting points by default. A connecting line can imply continuous behavior that was not actually measured. If a logarithmic axis is appropriate, state why and check that all plotted values are valid for that scale.

Scenario 4: Fitting a linear model

For a model of the form y = mx + b, SciPy provides a straightforward starting point:

from scipy.optimize import curve_fit


def linear_model(x, m, b):
    return m * x + b

params, covariance = curve_fit(
    linear_model,
    x,
    y,
    sigma=y_unc,
    absolute_sigma=True
)

m, b = params
parameter_uncertainties = np.sqrt(np.diag(covariance))
m_unc, b_unc = parameter_uncertainties
print(f"slope = {m:.4g} +/- {m_unc:.2g}")
print(f"intercept = {b:.4g} +/- {b_unc:.2g}")

The sigma argument tells the fit about the uncertainty assigned to each y value. absolute_sigma=True treats those values as absolute standard uncertainties rather than weights that will automatically be rescaled. Use this only when the uncertainties have a defensible meaning. If the uncertainty values are unknown or estimated poorly, say so in the report.

Scenario 5: Fitting a nonlinear model

Many physics relationships are not linear in their original variables. Examples include exponential decay, a pendulum period model, and power laws. Define the physical model directly:

def decay_model(t, amplitude, rate, offset):
    return amplitude * np.exp(-rate * t) + offset

initial_guess = [1.0, 0.5, 0.0]
params, covariance = curve_fit(
    decay_model,
    x,
    y,
    p0=initial_guess,
    sigma=y_unc,
    absolute_sigma=True,
    maxfev=10000
)

Initial guesses can affect whether a nonlinear optimizer finds a sensible solution. Use approximate values based on the graph and the physics, not arbitrary numbers. Add parameter bounds when the model requires them, such as a positive rate constant. A fit that converges is not automatically a physically appropriate fit.

Choosing a fitting method

SituationUseful starting methodCheck carefully
Linear relationship with comparable uncertaintiesWeighted or unweighted linear fitUnits of slope, intercept, and residual pattern
Known uncertainty for each measured outputcurve_fit with sigmaWhether uncertainties are standard uncertainties and whether they are independent
Nonlinear physical modelNonlinear least squaresInitial guesses, bounds, parameter correlation, and local minima
Uncertainty in both axesA method designed for errors in both variablesWhether ordinary least squares is inappropriate
Repeated or correlated measurementsModel-based or covariance-aware analysisIndependence assumptions and shared systematic effects

What to double-check

Residuals and model adequacy

Calculate residuals as measured values minus model predictions:

y_fit = linear_model(x, m, b)
residuals = y - y_fit

fig, ax = plt.subplots()
ax.axhline(0, color="black", linewidth=1)
ax.errorbar(x, residuals, yerr=y_unc, fmt="o")
ax.set_xlabel("Time (s)")
ax.set_ylabel("Residual (m)")
fig.tight_layout()
plt.show()

Residuals should be examined for structure. A curve, changing spread, or long run of positive or negative values may indicate that the model is incomplete, the uncertainty is misestimated, or the data are not independent. A smaller residual sum does not by itself prove that a more complicated model is better.

Uncertainty and significant figures

The square roots of the diagonal elements of the covariance matrix provide parameter uncertainties under the assumptions of the fit. They do not automatically include every source of uncertainty. Calibration, zero offset, timing resolution, environmental drift, and model limitations may contribute systematic effects that are not represented by point-to-point error bars.

Report values with sensible precision. A parameter uncertainty written as 0.0036 does not justify reporting the parameter to ten decimal places. State whether uncertainties are standard uncertainties, confidence intervals, or another interval type, and explain how they were obtained. For a broader report workflow, compare your analysis with the physics lab report template.

Physical interpretation

Translate fitted parameters back into physics. Check dimensions, sign, magnitude, and limiting behavior. For example, if a slope represents acceleration, its units should reduce to length per time squared. If an intercept should theoretically be zero, discuss whether the measured intercept is consistent with zero within uncertainty rather than silently forcing it to zero.

Common mistakes

  • Fitting before plotting: A plot can reveal a transcription error, saturation, drift, or a regime where the proposed model does not apply.
  • Mixing units: Combining centimetres with metres or milliseconds with seconds changes parameter values and can distort nonlinear relationships.
  • Using error bars as decoration: Error bars should represent a defined uncertainty, not a visual estimate added after the analysis.
  • Removing outliers without a record: Keep the original row, document the reason for exclusion, and report how the result changes if the point is retained.
  • Confusing goodness of fit with truth: A high fit-quality score cannot repair an incorrect physical model or biased measurements.
  • Over-rounding early: Keep adequate numerical precision during calculations and round only when presenting final results.
  • Overfitting small datasets: Extra parameters can follow random fluctuations and make physical interpretation less reliable.
  • Failing to save the environment: Record the Python version and important package versions when the result needs to be reproduced later.

These checks complement the conceptual work in other physics problems. For example, graphs in kinematics should still be interpreted using the relationships among position, velocity, and acceleration; see kinematics graphs explained. A script cannot replace that physical reasoning.

When to revisit

Revisit this workflow for every new dataset, not only when the code fails. In particular, repeat the checklist when the instrument, sampling interval, calibration, experimental range, or theoretical model changes. Recheck package syntax when major scientific Python libraries change, and verify that plotting defaults and fitting behavior still match your documented assumptions.

Before submitting a lab report or sharing a research result, run the analysis from the untouched raw file in a clean environment. Confirm that the figures regenerate, the reported parameters match the saved output, and the README explains units, exclusions, uncertainty sources, and model choice. If someone else cannot understand what the script did from the files provided, the analysis is not yet fully reproducible.

Action checklist: create a raw-data copy, write a column-and-unit dictionary, make a first plot, define the model in code, fit with documented uncertainty assumptions, inspect residuals, check dimensions, save figures and versions, and record the final interpretation in plain language. Then compare the result with an independent calculation or limiting-case estimate before treating it as a physics conclusion.

Related Topics

#Python#data analysis#physics labs#curve fitting#uncertainty analysis#research skills
P

Physics Direct Editorial Team

Physics Education Editors

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.