Chris Parmer — home

Rank-abundance (Whittaker) plot

Ecology

Example from the compendium of canonical charts

Ecology — Rank-abundance (Whittaker) plot

Python Code

"""Ecology — Rank-abundance (Whittaker) plot."""
from pathlib import Path

# ── Palette + theme (matching the Plotly Studio gallery these charts ship in) ──
VIOLET, TEAL, GREEN, PINK, ORANGE = "#845EEE", "#52B3D0", "#55B685", "#DA5597", "#E9A23B"
PRIMARY, SECONDARY = VIOLET, TEAL
COLORWAY = [VIOLET, TEAL, GREEN, PINK, ORANGE]
BG, TEXT, GRID, MUTED = "#ffffff", "#1c2024", "#d9d9e0", "#60646c"
FONT = "Inter, -apple-system, BlinkMacSystemFont, sans-serif"
COLORSCALE = [[0, "rgba(132, 94, 238, 0.05)"], [1, "rgba(132, 94, 238, 0.9)"]]


def apply_theme(fig):
    """Light gallery theme: white background, Inter font, soft gridlines."""
    fig.update_layout(
        paper_bgcolor=BG, plot_bgcolor=BG, colorway=COLORWAY,
        font=dict(family=FONT, color=TEXT, size=12),
        legend=dict(font=dict(color=TEXT)),
        hoverlabel=dict(bgcolor="#f0f0f3", font=dict(color=TEXT, family=FONT), bordercolor=GRID),
    )
    fig.update_xaxes(gridcolor=GRID, linecolor=GRID, zerolinecolor=GRID)
    fig.update_yaxes(gridcolor=GRID, linecolor=GRID, zerolinecolor=GRID)


def fetch_csv(url, **kwargs):
    import io
    import pandas as pd
    import requests
    r = requests.get(url, timeout=60)
    r.raise_for_status()
    return pd.read_csv(io.StringIO(r.text), **kwargs)


def fetch_json(url):
    import requests
    r = requests.get(url, timeout=60)
    r.raise_for_status()
    return r.json()

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,
    )
    apply_theme(fig)
    return fig


fig = generate()
fig.show()

Made with Plotly