Rank-abundance (Whittaker) plot
Ecology
Example from the compendium of canonical charts
Python Code
"""Ecology — Rank-abundance (Whittaker) plot."""
import pandas as pd
import numpy as np
import plotly.graph_objects as go
URL = "https://raw.githubusercontent.com/weecology/portal-teachingdb/master/surveys.csv"
def generate():
print("fetching Portal Teaching DB surveys …")
try:
df = fetch_csv(URL)
print(f" {len(df):,} rows, cols: {list(df.columns)}")
counts = (
df["species_id"]
.dropna()
.value_counts()
.reset_index()
)
counts.columns = ["species_id", "count"]
used_synthetic = False
except Exception as e:
print(f" fetch failed ({e}); using synthetic species counts")
used_synthetic = True
rng = np.random.default_rng(42)
species = [f"SP{i:02d}" for i in range(1, 25)]
# power-law distribution
counts_arr = np.round(5000 * (1 / np.arange(1, 25)) ** 0.8).astype(int)
counts_arr += rng.integers(0, 50, size=24)
counts = pd.DataFrame({"species_id": species, "count": counts_arr})
counts = counts.sort_values("count", ascending=False).reset_index(drop=True)
counts["rank"] = counts.index + 1
# label top 5
annotations = []
for _, row in counts.head(5).iterrows():
annotations.append(dict(
x=row["rank"],
y=np.log10(row["count"]),
text=row["species_id"],
showarrow=True,
arrowhead=2,
arrowsize=0.8,
ax=20, ay=-20,
font=dict(size=11),
))
fig = go.Figure([
go.Scatter(
x=counts["rank"],
y=counts["count"],
mode="lines+markers",
marker=dict(color=VIOLET, size=7),
line=dict(color=VIOLET, width=2),
hovertemplate="Rank %{x}<br>%{customdata}: %{y:,} captures<extra></extra>",
customdata=counts["species_id"],
)
])
fig.update_layout(
xaxis=dict(title="Rank"),
yaxis=dict(title="Number of captures", type="log"),
annotations=annotations,
margin=dict(t=40, b=60, l=80, r=40),
height=500,
)
return fig
if __name__ == "__main__":
generate()
Made with Plotly