Back to the blog

How to Identify a Statistical Distribution Using Python

In engineering, mining, and process analysis, we constantly work with data that does not always behave as a normal distribution. Metallurgical recoveries, equipment failure times, particle sizes, or reagent consumption follow different distribution families — lognormal, Weibull, gamma, beta — and assuming normality when it does not apply can invalidate confidence intervals, hypothesis tests, and Monte Carlo simulations.

In this article, I will show a reproducible Python workflow to identify the statistical distribution that best describes a data set, combining visual exploration, maximum likelihood fitting, goodness-of-fit tests, and information criteria.


1. Why does identifying the correct distribution matter?

Identifying the underlying distribution family has practical implications:

  • Hypothesis tests: the t-test, ANOVA, or classical intervals assume normality.
  • Process control: the 3σ limits lose meaning if the variable is skewed.
  • Monte Carlo simulation: sampling from the wrong distribution biases all conclusions.
  • Reliability: the time to failure of pumps, motors, or liners is usually Weibull, not normal.
  • Particle size distribution / assay chemistry: particle sizes and mineral grades are typically lognormal.

The general workflow is:

Visual exploration  →  Reasonable candidates  →  MLE fitting  →
Goodness of fit  →  Information criteria  →  Visual validation

2. Libraries and example data

We will use the standard scientific stack:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats
import warnings
warnings.filterwarnings("ignore")

rng = np.random.default_rng(seed=42)

As an example, we will generate a synthetic sample that simulates copper recovery (%) from laboratory flotation tests — typically skewed and bounded in [0, 100]:

# Simulated sample: Cu recovery in a rougher circuit
datos = rng.lognormal(mean=np.log(85), sigma=0.08, size=200)
datos = np.clip(datos, 0, 100)

In a real case you would replace this line with pd.read_excel("your_data.xlsx")[column].values.


3. Initial exploration

Before fitting anything, look at your data. Calculate descriptive statistics and plot.

3.1 Descriptive statistics

desc = pd.Series(datos).describe()
print(desc)
print(f"Skewness: {stats.skew(datos):.3f}")
print(f"Kurtosis (excess):    {stats.kurtosis(datos):.3f}")

Quick interpretation:

Indicator Suggested distribution
Skewness ≈ 0, kurtosis ≈ 0 Normal
Skewness > 0, right tail Lognormal, gamma, Weibull
Skewness < 0, left tail Beta (β > α), inverted Weibull
Data bounded in [0, 1] or [a, b] Beta, uniform
Integer count data Poisson, negative binomial

3.2 Histogram and KDE

fig, ax = plt.subplots(1, 2, figsize=(12, 4))

ax[0].hist(datos, bins=25, density=True, alpha=0.6, edgecolor="black")
ax[0].set_title("Histogram")
ax[0].set_xlabel("Cu Recovery (%)")

pd.Series(datos).plot.kde(ax=ax[1])
ax[1].set_title("Estimated density (KDE)")
plt.tight_layout()
plt.show()

3.3 Q-Q plot against the normal

A cheap first diagnostic:

stats.probplot(datos, dist="norm", plot=plt)
plt.title("Q-Q plot vs Normal")
plt.show()

If the points fall on the line, there is good evidence of normality. If they curve at the extremes, the tail is heavier or lighter than normal.


4. Reasonable candidates based on domain

There is no sense in testing ~80 distributions in SciPy. We choose plausible candidates based on the support of the variable and the physical phenomenon:

Variable Typical candidates
Recovery, grade, % solids Beta, lognormal, gamma
Time to failure Weibull, exponential, lognormal
Particle size Lognormal, Weibull (Rosin-Rammler)
Measurement error Normal, t-Student
Counts (particles, events) Poisson, negative binomial

For our example we will consider four continuous candidates:

candidatos = {
    "Normal":     stats.norm,
    "Lognormal":  stats.lognorm,
    "Gamma":      stats.gamma,
    "Weibull":    stats.weibull_min,
}

5. Maximum likelihood estimation (MLE) fitting

SciPy fits the parameters of any continuous distribution with .fit(), which solves the maximum likelihood problem:

\[\hat{\theta} = \arg\max_{\theta} \prod_{i=1}^{n} f(x_i \mid \theta)\]
ajustes = {}
for nombre, dist in candidatos.items():
    params = dist.fit(datos)
    ajustes[nombre] = {"dist": dist, "params": params}
    print(f"{nombre:12s} → parameters: {np.round(params, 4)}")

Note: in SciPy, the last two parameters are always loc and scale. Shape parameters come first. For lognorm the first parameter is s (sigma of the lognormal); for weibull_min it is c (Weibull shape parameter k).


6. Goodness-of-fit tests

Three classic tests, in order of use:

6.1 Kolmogorov–Smirnov (KS)

Compares the empirical CDF with the theoretical one. Useful but not very sensitive to the tails.

for nombre, info in ajustes.items():
    dist, params = info["dist"], info["params"]
    D, p = stats.kstest(datos, dist.name, args=params)
    print(f"{nombre:12s}  D={D:.4f}  p={p:.4f}")

Rule of thumb: if p > 0.05, you do not reject the hypothesis that the data comes from that distribution.

6.2 Anderson–Darling

More sensitive to the tails than KS. SciPy implements it for normal, exponential, logistic, Gumbel, and Weibull:

result = stats.anderson(datos, dist="norm")
print(f"AD statistic: {result.statistic:.4f}")
for sl, cv in zip(result.significance_level, result.critical_values):
    print(f"  Level {sl:.1f}%  critical value {cv:.3f}")

6.3 Shapiro–Wilk (normality only)

Powerful with small to medium samples:

W, p = stats.shapiro(datos)
print(f"Shapiro-Wilk: W={W:.4f}  p={p:.4f}")

Warning: with very large n (for example n > 2000), almost any test rejects normality for trivial differences. In that regime, prioritize graphical tools and information criteria.


7. Selecting the best model: AIC and BIC

Goodness-of-fit tests tell you if a model is compatible with the data, not which is best. For that, information criteria are used, which penalize the number of parameters:

\[\mathrm{AIC} = 2k - 2\ln(\hat{L})\]
\[\mathrm{BIC} = k \ln(n) - 2 \ln(\hat{L})\]

Where k is the number of parameters and L is the likelihood. Lower is better. BIC penalizes complexity more strongly and tends to prefer simpler models.

def aic_bic(dados, dist, params):
    logL = np.sum(dist.logpdf(dados, *params))
    k = len(params)
    n = len(dados)
    aic = 2 * k - 2 * logL
    bic = k * np.log(n) - 2 * logL
    return aic, bic, logL

resumen = []
for nombre, info in ajustes.items():
    aic, bic, logL = aic_bic(datos, info["dist"], info["params"])
    resumen.append({"Distribución": nombre, "logL": logL, "AIC": aic, "BIC": bic})

df = pd.DataFrame(resumen).sort_values("AIC")
print(df.to_string(index=False))

The model in the top row has the best fit/complexity trade-off.


8. Visual validation: the step never to skip

Two final plots confirm (or refute) the choice: histogram with overlaid densities + Q-Q plot of the best candidate.

Fitted candidates + Q-Q plot

On the left, the histogram with the 4 candidates overlaid: the red curve (Lognormal) follows the empirical shape much better than the blue (Normal). On the right, the Q-Q plot against the Lognormal with \(R^2 \approx 1\) confirms that the observed quantiles fall on the theoretical diagonal across the full range.

x = np.linspace(datos.min(), datos.max(), 500)
plt.hist(datos, bins=25, density=True, alpha=0.5, edgecolor="black", label="Data")
for nombre, info in ajustes.items():
    plt.plot(x, info["dist"].pdf(x, *info["params"]), label=nombre, lw=2)
plt.legend()
plt.xlabel("Cu Recovery (%)")
plt.ylabel("Density")
plt.title("Fitted candidates")
plt.show()

# Q-Q plot of the best
mejor = df.iloc[0]["Distribución"]
dist, params = ajustes[mejor]["dist"], ajustes[mejor]["params"]
stats.probplot(datos, dist=dist, sparams=params, plot=plt)
plt.title(f"Q-Q plot vs {mejor}")
plt.show()

9. Automated workflow

To reuse the analysis, a function that takes the data array and a list of candidates:

def identificar_distribucion(datos, candidatos=None):
    if candidatos is None:
        candidatos = {
            "Normal":    stats.norm,
            "Lognormal": stats.lognorm,
            "Gamma":     stats.gamma,
            "Weibull":   stats.weibull_min,
            "Beta":      stats.beta,
            "Expon":     stats.expon,
        }

    filas = []
    for nombre, dist in candidatos.items():
        try:
            params = dist.fit(datos)
            logL = np.sum(dist.logpdf(datos, *params))
            k, n = len(params), len(datos)
            aic = 2 * k - 2 * logL
            bic = k * np.log(n) - 2 * logL
            D, p_ks = stats.kstest(datos, dist.name, args=params)
            filas.append({
                "Distribución": nombre,
                "AIC": aic,
                "BIC": bic,
                "KS_D": D,
                "KS_pvalue": p_ks,
                "params": params,
            })
        except Exception as e:
            print(f"{nombre}: could not fit ({e})")

    return pd.DataFrame(filas).sort_values("AIC").reset_index(drop=True)

resultados = identificar_distribucion(datos)
print(resultados[["Distribución", "AIC", "BIC", "KS_D", "KS_pvalue"]])

10. Final recommendations

  1. Start with the phenomenon, not the data. If you measure a time to failure, start by testing Weibull and exponential, not normal.
  2. Don't rely on a single test. Combine KS, AD, or Shapiro with AIC/BIC and Q-Q plots.
  3. Beware of large samples. With n > 2000, tests reject normality for irrelevant differences; prioritize visuals.
  4. Document the fitted parameters. Note them in the report along with sample size and SciPy version — your future self will be grateful.
  5. Consider transforming before forcing a fit. Lognormally distributed data fitted on a log scale are usually approximately normal and allow you to use standard tools.
  6. If nothing fits, the empirical distribution (ECDF) is also a valid answer. Not every phenomenon fits a parametric family.

Closing

Identifying a distribution is not an academic exercise: it conditions the validity of everything that comes next — confidence intervals, simulations, control charts, reliability models. The workflow shown here (exploration → candidates → MLE → goodness of fit → AIC/BIC → visual validation) is transferable to practically any continuous variable you encounter in plant, lab, or business model.

If you work with metallurgical process data, reagent consumption, or equipment reliability, this workflow will serve you as a base template.

Back to the blog