The Galápagos plant species–area relationship¶
A complete analysis with sars, from the raw island data to a model-averaged
curve with confidence intervals and a check for a small-island effect, then a threshold
with confidence intervals on a larger dataset, the Aegean plants. Every step
is one function call, and every result is a plain object you can inspect, so the
same sequence works for your own data (see the end).
The data are Preston's (1962) counts of plant species on 16 Galápagos islands,
with island areas in km², as shipped in the R sars package (Isabela is
excluded). They are bundled with the package as load_galap().
import warnings
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import sars
The data¶
A sars dataset is a pandas.DataFrame with two columns, area and species.
galap = sars.load_galap()
galap.sort_values("area").reset_index(drop=True)
| area | species | |
|---|---|---|
| 0 | 0.52 | 48 |
| 1 | 2.33 | 7 |
| 2 | 2.59 | 52 |
| 3 | 4.66 | 14 |
| 4 | 4.84 | 42 |
| 5 | 11.40 | 22 |
| 6 | 18.39 | 103 |
| 7 | 19.42 | 48 |
| 8 | 46.62 | 79 |
| 9 | 51.80 | 119 |
| 10 | 116.55 | 47 |
| 11 | 165.76 | 319 |
| 12 | 505.05 | 306 |
| 13 | 525.77 | 224 |
| 14 | 634.55 | 80 |
| 15 | 1007.51 | 193 |
galap.describe().T
| count | mean | std | min | 25% | 50% | 75% | max | |
|---|---|---|---|---|---|---|---|---|
| area | 16.0 | 194.8600 | 304.251296 | 0.52 | 4.795 | 33.02 | 250.5825 | 1007.51 |
| species | 16.0 | 106.4375 | 100.327443 | 7.00 | 45.750 | 65.50 | 137.5000 | 319.00 |
Area spans more than three orders of magnitude, so the natural view is a log–log plot. The spread at small areas is already visible: islands under 10 km² have anywhere from 7 to 52 species.
ax = galap.plot.scatter(x="area", y="species", s=40)
ax.set(
xscale="log",
yscale="log",
xlabel="Area (km²)",
ylabel="Species",
title="Galápagos plants: observed richness",
)
plt.show()
One model: the power law¶
Arrhenius' power law, \(S = cA^z\), is the classic SAR model. sar_power() fits it by
non-linear least squares and returns a SARFit with the parameters, goodness of fit
and information criteria.
power = sars.sar_power(galap)
power
SARFit(model='power', c=33.1803 z=0.2832, R²=0.4912, AICc=189.03)
print("parameters:", {k: round(float(v), 4) for k, v in power.params.items()})
print(
"R²:", round(power.r_squared, 4), " AICc:", round(power.aicc, 2), " converged:", power.converged
)
parameters: {'c': 33.1803, 'z': 0.2832}
R²: 0.4912 AICc: 189.03 converged: True
param_table() gives the parameters standard errors, t tests and confidence intervals
(the table R sars reports as a fit's sigConf). The exponent is clearly above zero
(p = 0.013), but sixteen islands don't pin it down: its 95% interval runs from 0.07 to
0.50. The interval for c even includes zero.
power.param_table().round(4)
| estimate | std_error | t_value | p_value | ci_lower | ci_upper | |
|---|---|---|---|---|---|---|
| parameter | ||||||
| c | 33.1803 | 19.2423 | 1.7243 | 0.1066 | -8.0903 | 74.4509 |
| z | 0.2832 | 0.0994 | 2.8499 | 0.0129 | 0.0701 | 0.4963 |
predict() evaluates the fitted curve at any area, here for islands of 1, 10, 100
and 1000 km².
areas = np.array([1.0, 10.0, 100.0, 1000.0])
pd.DataFrame({"area": areas, "predicted species": power.predict(areas).round(1)})
| area | predicted species | |
|---|---|---|
| 0 | 1.0 | 33.2 |
| 1 | 10.0 | 63.7 |
| 2 | 100.0 | 122.2 |
| 3 | 1000.0 | 234.6 |
plot_fit() draws the fitted curve over the observations, on linear or log axes, and
plot_residuals() shows residuals against fitted values. The power law explains about
half the variance here; the residual plot shows why, with the small islands scattering
widely around the curve.
fig, axes = plt.subplots(1, 3, figsize=(15, 4.2))
sars.plot_fit(power, ax=axes[0])
sars.plot_fit(power, ax=axes[1], log=True)
sars.plot_residuals(power, ax=axes[2])
fig.tight_layout()
plt.show()
All twenty models¶
There is no reason to assume the power law is the right shape. sar_multi() fits every
model in the package and returns a MultiSARFit whose summary ranks them by AICc,
with Akaike weights (the relative support for each model, summing to one), each model's
general shape and, for models that have one, the asymptote. The shape is a property of
the model (linear, convex, sigmoid, or convex/sigmoid where its parameters decide), not a test
of the fitted curve. observed_shape is the shape each fitted curve actually takes
over the observed areas.
multi = sars.sar_multi(galap)
cols = ["model", "R2", "AICc", "delta_AICc", "weight", "shape", "observed_shape", "asymptote"]
multi.summary[cols].round(3)
| model | R2 | AICc | delta_AICc | weight | shape | observed_shape | asymptote | |
|---|---|---|---|---|---|---|---|---|
| 0 | negexpo | 0.557 | 186.832 | 0.000 | 0.198 | convex | convex | 207.926 |
| 1 | monod | 0.545 | 187.246 | 0.414 | 0.161 | convex | convex | 222.342 |
| 2 | koba | 0.521 | 188.073 | 1.241 | 0.107 | convex | convex | NaN |
| 3 | power | 0.491 | 189.031 | 2.199 | 0.066 | convex | convex | NaN |
| 4 | loga | 0.486 | 189.191 | 2.359 | 0.061 | convex | convex | NaN |
| 5 | p1 | 0.589 | 189.246 | 2.414 | 0.059 | convex/sigmoid | none | NaN |
| 6 | gompertz | 0.585 | 189.393 | 2.561 | 0.055 | sigmoid | sigmoid | 210.852 |
| 7 | asymp | 0.578 | 189.672 | 2.840 | 0.048 | convex/sigmoid | convex | 209.121 |
| 8 | chapman | 0.565 | 190.171 | 3.339 | 0.037 | sigmoid | convex | 208.015 |
| 9 | weibull3 | 0.561 | 190.324 | 3.493 | 0.035 | sigmoid | convex | 208.021 |
| 10 | ratio | 0.556 | 190.494 | 3.662 | 0.032 | convex | convex | 227.895 |
| 11 | epm1 | 0.550 | 190.717 | 3.885 | 0.028 | convex/sigmoid | none | NaN |
| 12 | mmf | 0.545 | 190.882 | 4.050 | 0.026 | convex/sigmoid | convex | 222.956 |
| 13 | heleg | 0.545 | 190.882 | 4.050 | 0.026 | convex/sigmoid | convex | 222.956 |
| 14 | p2 | 0.521 | 191.712 | 4.880 | 0.017 | sigmoid | sigmoid | NaN |
| 15 | powerR | 0.503 | 192.283 | 5.451 | 0.013 | convex | convex | NaN |
| 16 | epm2 | 0.502 | 192.329 | 5.497 | 0.013 | sigmoid | none | NaN |
| 17 | weibull4 | 0.594 | 193.437 | 6.606 | 0.007 | sigmoid | convex | 208.414 |
| 18 | linear | 0.316 | 193.765 | 6.934 | 0.006 | linear | linear | NaN |
| 19 | betap | 0.560 | 194.698 | 7.866 | 0.004 | sigmoid | convex | 208.062 |
Several convex models fit about equally well, and the best has a weight well under 0.5:
the data don't single out one functional form. That is the usual situation with a
handful of islands, and the reason for the next step. plot_multi() overlays the top
models; fits holds the individual SARFit objects if you need one of them.
Most fits are convex over the observed areas, sigmoid models included: chapman, weibull3,
weibull4 and betap bend upwards only below the smallest island. gompertz and p2 are
sigmoid over the data. p1 and epm1 peak near 400 km² and turn down at the largest
islands, and epm2 dips among the smallest: richness falls somewhere, so none of the
shapes fits (none).
sars.plot_multi(multi, top_n=5)
plt.show()
Model averaging¶
Rather than choosing a winner, sar_average() weights each model's prediction by its
Akaike weight. The AveragedSAR it returns has the weights and a predict() like a
single fit. Compared with the power law alone, the averaged curve is lower at the
smallest areas, where the leading asymptotic models pass near the origin, and flatter
at the largest.
avg = sars.sar_average(galap)
weights = pd.Series(avg.weights, name="weight").sort_values(ascending=False)
weights.head(8).round(3)
negexpo 0.198 monod 0.161 koba 0.107 power 0.066 loga 0.061 p1 0.059 gompertz 0.055 asymp 0.048 Name: weight, dtype: float64
pd.DataFrame(
{
"area": areas,
"power law": power.predict(areas).round(1),
"model average": avg.predict(areas).round(1),
}
)
| area | power law | model average | |
|---|---|---|---|
| 0 | 1.0 | 33.2 | 10.9 |
| 1 | 10.0 | 63.7 | 42.7 |
| 2 | 100.0 | 122.2 | 148.1 |
| 3 | 1000.0 | 234.6 | 210.0 |
Checking the residuals¶
The average weighs every model that converged. Least squares, and the AICc built on it,
assume residuals that are normal and equally spread, and a curve that predicts negative
richness isn't usable. sar_average(), like sar_multi() and bootstrap_ci(), can leave
out the models that fail such checks, as R sars's sar_average does: here a
Shapiro–Wilk test of normality, the correlation of the squared residuals with the fitted
values for equal spread, and a check for negative predictions at the observed areas.
with warnings.catch_warnings():
warnings.simplefilter("ignore") # the reasons are printed below
checked = sars.sar_average(
galap, normality="shapiro", homoscedasticity="cor.fitted", neg_check=True
)
for model, reason in checked.multi.excluded.items():
print(f"{model}: {reason}")
print(f"\n{len(checked.weights)} models averaged")
power: residual variance not constant (spearman correlation of squared residuals with fitted values = 0.529, p = 0.0373 < 0.05) epm2: residual variance not constant (spearman correlation of squared residuals with fitted values = 0.559, p = 0.0267 < 0.05) loga: negative fitted values linear: residuals not normal (shapiro p = 0.0202 < 0.05) 16 models averaged
Four models fail, the power law among them: its residuals spread out as richness grows.
excluded says why each was left out (sar_average also warns, silenced above since
the reasons are printed). Averaging the sixteen
that pass moves the curve by a few species:
pd.DataFrame(
{
"area": areas,
"all models": avg.predict(areas).round(1),
"models that pass": checked.predict(areas).round(1),
}
)
| area | all models | models that pass | |
|---|---|---|---|
| 0 | 1.0 | 10.9 | 9.1 |
| 1 | 10.0 | 42.7 | 38.7 |
| 2 | 100.0 | 148.1 | 151.5 |
| 3 | 1000.0 | 210.0 | 207.5 |
sar_pred() collects predictions from any fit into one table, with a row per model and
area. Here are the leading models' predictions for islands of 50 and 500 km²:
predictions = sars.sar_pred(multi, [50.0, 500.0])
table = predictions.pivot(index="model", columns="area", values="prediction")
table.reindex(multi.summary["model"]).head(6).round(1)
| area | 50.0 | 500.0 |
|---|---|---|
| model | ||
| negexpo | 106.3 | 207.8 |
| monod | 114.9 | 203.3 |
| koba | 109.0 | 198.8 |
| power | 100.5 | 192.8 |
| loga | 118.7 | 188.5 |
| p1 | 109.1 | 227.8 |
Bootstrap confidence intervals¶
bootstrap_ci() resamples the islands, refits and re-averages on each resample, and
returns percentile intervals for the averaged curve on a grid of areas. The default
method="fast" warm-starts every refit from the parameters fitted to the original data;
method="full" repeats the whole grid search per resample and is much slower. Pass a
seeded numpy generator for a reproducible result. Three hundred resamples take about
a minute here; use more for a publication figure.
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
ci = sars.bootstrap_ci(galap, n_boot=300, rng=np.random.default_rng(1))
print(
f"{ci.n_boot} resamples, {ci.n_models_attempted} models each, {int(ci.conf * 100)}% intervals"
)
for w in caught:
print("Warning:", w.message)
300 resamples, 20 models each, 95% intervals Warning: The bootstrap mean is outside the central 95% of the resample predictions at 43 of 98 areas: a few resamples' predictions run away there. Use the averaged fit's own prediction as the central curve, or the median as the interval's centre. Warning: The interval's upper bound exceeds 10 times the largest observed richness at 2 of 98 areas (from 0.52 to 0.6069): there more than 2.5% of the resamples' predictions run away, usually because few observations lie near those areas and resamples that leave them out extrapolate. Read the interval as unbounded there.
rows = [np.argmin(abs(ci.area_grid - a)) for a in (10.0, 100.0, 500.0, 1000.0)]
at = ci.area_grid[rows]
pd.DataFrame(
{
"area": at.round(1),
"lower": ci.lower[rows].round(1),
"model average": avg.predict(at).round(1),
"upper": ci.upper[rows].round(1),
}
)
| area | lower | model average | upper | |
|---|---|---|---|---|
| 0 | 9.8 | 0.1 | 42.1 | 61.3 |
| 1 | 99.3 | 43.8 | 147.7 | 298.8 |
| 2 | 493.7 | 116.4 | 204.0 | 327.4 |
| 3 | 1007.5 | 8.0 | 210.1 | 514.4 |
plot_average() draws the averaged curve, and shades the interval when given the
bootstrap result. The band is wide and ragged, and honestly so: with sixteen islands, a
resample that repeats a few of them lets the three- and four-parameter models fit
wildly, and the gap between the mid-sized and the largest islands is where that shows.
More islands, or a smaller candidate set chosen on biological grounds, narrows it. Use
the averaged fit's own prediction as the central curve, or the bootstrap median as
the interval's centre, rather than the bootstrap mean, which a few divergent
resamples dominate.
fig, axes = plt.subplots(1, 2, figsize=(11, 4.2))
sars.plot_average(avg, boot=ci, ax=axes[0])
sars.plot_average(avg, boot=ci, ax=axes[1])
axes[1].set(xscale="log", yscale="log", title="Model average (log axes)")
fig.tight_layout()
plt.show()
Is there a small-island effect?¶
Below some area, richness may stop responding to area at all: the small-island effect.
sar_threshold() fits piecewise models to species against the natural log of area and
compares them
with a plain log-linear fit by AICc. ContOne is a continuous two-slope line with one
breakpoint; ZslopeOne has a flat left segment, the small-island effect proper;
Linear is the no-breakpoint baseline. Pass log_area=False to fit on area itself.
th = sars.sar_threshold(galap)
print(th)
th.summary.round(3)
ThresholdFit(best='Linear')
| model | breakpoint | breakpoint_area | breakpoint2 | breakpoint2_area | AIC | AICc | BIC | R2 | |
|---|---|---|---|---|---|---|---|---|---|
| 0 | Linear | NaN | NaN | NaN | NaN | 187.191 | 189.191 | 189.509 | 0.486 |
| 1 | ZslopeOne | 2.032 | 7.627 | NaN | NaN | 187.579 | 191.216 | 190.670 | 0.535 |
| 2 | ContOne | 1.832 | 6.244 | NaN | NaN | 189.528 | 195.528 | 193.391 | 0.537 |
The models are fitted on the natural log of area, so breakpoint is on that scale;
breakpoint_area beside it is the same point in km² (the result has a breakpoint_area
attribute too). For the Galápagos plants the log-linear model wins; the flat-then-slope
model trails it by two AICc units and the two-slope model by six, with only sixteen
islands behind them. No clear small-island effect in these data.
grid = np.geomspace(galap["area"].min(), galap["area"].max(), 200)
ax = galap.plot.scatter(x="area", y="species", s=40, label="observed")
ax.plot(grid, th.predict(grid), color="C1", label=f"best threshold model: {th.best_model}")
ax.set(
xscale="log",
xlabel="Area (km², log scale)",
ylabel="Species",
title="Species against the natural log of area",
)
ax.legend()
plt.show()
A threshold, with an interval¶
Sixteen islands give a threshold little to work with. The package bundles three larger island
datasets, the usual examples for threshold models: load_aegean(), load_aegean2() and
load_niering(). On the 173 Aegean islands of load_aegean2() the two-slope model wins
by a wide margin, with its breakpoint near 10 km²:
aegean2 = sars.load_aegean2()
th2 = sars.sar_threshold(aegean2)
print(th2)
th2.summary[["model", "breakpoint", "breakpoint_area", "AICc", "R2"]].round(3)
ThresholdFit(best='ContOne', breakpoint=2.305 (ln area), breakpoint_area=10.02)
| model | breakpoint | breakpoint_area | AICc | R2 | |
|---|---|---|---|---|---|
| 0 | ContOne | 2.305 | 10.020 | 2046.165 | 0.943 |
| 1 | ZslopeOne | 1.375 | 3.953 | 2061.765 | 0.937 |
| 2 | Linear | NaN | NaN | 2305.190 | 0.740 |
threshold_ci() puts an interval on the breakpoint: by default a residual bootstrap, or,
for ContOne and ZslopeOne, an inverted F test (method="F"). The bootstrap places the
threshold between about 7 and 13 km², the F test between about 6 and 15 km². plot_threshold() draws
the fit on the scale it was fitted on, with the interval shaded.
boot = sars.threshold_ci(th2, model="ContOne", rng=np.random.default_rng(1))
f_test = sars.threshold_ci(th2, model="ContOne", method="F")
print(boot)
print(f_test)
ThresholdCI(model='ContOne', breakpoints_area=(10.02 [7.349, 13.13]), conf=0.95, n_boot=1000) ThresholdCI(model='ContOne', breakpoints_area=(10.02 [5.898, 14.8]), conf=0.95, method='F')
sars.plot_threshold(th2, model="ContOne", ci=boot)
plt.show()
Your own data¶
Any DataFrame with area and species columns works in place of galap, and the
I/O adapters build one from a CSV with other column names, a GeoDataFrame (area from
the geometries) or a pyiNaturalist summary:
islands = sars.from_csv("islands.csv", area_col="island_area", species_col="richness")
multi = sars.sar_multi(islands)
Two things to keep in mind. Fitting twenty non-linear models with a multi-start search takes a few seconds per call, and the bootstrap repeats it per resample. And the threshold models need at least seven observations to place a breakpoint; with fewer, only the linear baseline is fitted and a warning says so.
References¶
- Arrhenius O (1921). Species and area. Journal of Ecology, 9, 95–99.
- Matthews TJ, Triantis KA, Whittaker RJ, Guilhaumon F (2019). sars: an R package for fitting, evaluating and comparing species–area relationship models. Ecography, 42, 1446–1455.
- Matthews TJ, Rigal F (2021). Thresholds and the species–area relationship. Frontiers of Biogeography, 13, e49404.
- Preston FW (1962). The canonical distribution of commonness and rarity. Ecology, 43, 185–215, 410–432.