Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                

Basic Ternary Plot in Seaborn (Python)

The same plot in 14 other libraries — Python: Altair, Bokeh, lets-plot, Matplotlib, Plotly, plotnine, Pygal; R: ggplot2; Julia: Makie.jl; JavaScript: Chart.js, D3.js, Apache ECharts, Highcharts, MUI X Charts. Compare all 15 side by side: Basic Ternary Plot in Python, R, Julia and JavaScript.

A ternary plot displays three-component compositional data on an equilateral triangle where each vertex represents 100% of one component. Points inside the triangle show compositions that sum to a constant total (usually 100%), with position indicating relative proportions. This visualization is essential for data where three variables are interdependent and constrained to sum to a fixed value.

Basic Ternary Plot rendered with Seaborn

Renders

Python source (Seaborn)

""" anyplot.ai
ternary-basic: Basic Ternary Plot
Library: seaborn 0.13.2 | Python 3.14.10
Quality: 82/100 | Updated: 2026-12-02
"""

import os

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns


# Theme tokens (see prompts/default-style-guide.md)
THEME = os.getenv("ANYPLOT_THEME", "light")
PAGE_BG = "#FAF8F1" if THEME == "light" else "#1A1A17"
INK = "#1A1A17" if THEME == "light" else "#F0EFE8"
INK_SOFT = "#4A4A44" if THEME == "light" else "#B8B7B0"
BRAND = "#009E73"  # Imprint palette position 1

# Set seaborn/matplotlib theme
sns.set_theme(
    style="ticks",
    rc={
        "figure.facecolor": PAGE_BG,
        "axes.facecolor": PAGE_BG,
        "axes.edgecolor": INK_SOFT,
        "axes.labelcolor": INK,
        "text.color": INK,
        "xtick.color": INK_SOFT,
        "ytick.color": INK_SOFT,
        "grid.color": INK,
        "grid.alpha": 0.15,
    },
)

# Columns: set these to your table's column names
SAND = "Sand"  # role: component_a
SILT = "Silt"  # role: component_b
CLAY = "Clay"  # role: component_c

# Data: replace this block with your own table, for example df = pd.read_csv("soil.csv")
# Soil texture samples (percent sand, silt, clay); each row sums to 100.
np.random.seed(42)
raw = np.random.dirichlet(alpha=[1.0, 1.0, 1.0], size=50) * 100
df = pd.DataFrame({SAND: raw[:, 0], SILT: raw[:, 1], CLAY: raw[:, 2]})

# Plot
# Barycentric -> Cartesian. Vertices: Sand bottom-left (0, 0), Silt bottom-right (1, 0), Clay top.
sqrt3_2 = np.sqrt(3) / 2
total = df[[SAND, SILT, CLAY]].sum(axis=1)
sand_norm = df[SAND] / total
silt_norm = df[SILT] / total
clay_norm = df[CLAY] / total
points = pd.DataFrame({"x": 0.5 * (2 * silt_norm + clay_norm), "y": sqrt3_2 * clay_norm})

# Canonical square canvas: figsize (6, 6) x dpi 400 -> 2400x2400 px
fig, ax = plt.subplots(figsize=(6, 6), dpi=400, facecolor=PAGE_BG)

# Triangle outline
triangle = np.array([[0, 0], [1, 0], [0.5, sqrt3_2], [0, 0]])
ax.plot(triangle[:, 0], triangle[:, 1], color=INK_SOFT, linewidth=1, zorder=5)

# Grid lines at 10% intervals, each set parallel to the side opposite its vertex
grid_lw = 0.5
for level in np.arange(0.1, 0.95, 0.1):
    # Constant Clay: parallel to the bottom edge
    ax.plot([0.5 * level, 1 - 0.5 * level], [sqrt3_2 * level] * 2, color=INK, alpha=0.15, linewidth=grid_lw, zorder=2)
    # Constant Silt: parallel to the left edge
    ax.plot([level, 0.5 + 0.5 * level], [0, sqrt3_2 * (1 - level)], color=INK, alpha=0.15, linewidth=grid_lw, zorder=2)
    # Constant Sand: parallel to the right edge
    ax.plot(
        [0.5 * (1 - level), 1 - level], [sqrt3_2 * (1 - level), 0], color=INK, alpha=0.15, linewidth=grid_lw, zorder=2
    )

# Edge ticks at 20% intervals
tick_length = 0.02
for level in np.arange(0.2, 0.85, 0.2):
    label = f"{round(level * 100)}%"

    # Bottom edge: Silt increasing left to right
    ax.plot([level, level], [-tick_length, 0], color=INK_SOFT, linewidth=0.75, zorder=5)
    ax.text(level, -0.05, label, ha="center", va="top", fontsize=8, color=INK_SOFT)

    # Left edge: Sand increasing downward (Sand = 100% - Clay on this edge)
    x_tick, y_tick = 0.5 * level, sqrt3_2 * level
    dx, dy = -tick_length * np.cos(np.pi / 6), -tick_length * np.sin(np.pi / 6)
    ax.plot([x_tick, x_tick + dx], [y_tick, y_tick + dy], color=INK_SOFT, linewidth=0.75, zorder=5)
    ax.text(
        x_tick + dx - 0.03,
        y_tick + dy + 0.01,
        f"{round((1 - level) * 100)}%",
        ha="right",
        va="center",
        fontsize=8,
        color=INK_SOFT,
    )

    # Right edge: Clay increasing upward
    x_tick, y_tick = 1 - 0.5 * level, sqrt3_2 * level
    dx, dy = tick_length * np.cos(np.pi / 6), -tick_length * np.sin(np.pi / 6)
    ax.plot([x_tick, x_tick + dx], [y_tick, y_tick + dy], color=INK_SOFT, linewidth=0.75, zorder=5)
    ax.text(x_tick + dx + 0.03, y_tick + dy + 0.01, label, ha="left", va="center", fontsize=8, color=INK_SOFT)

# Data points
sns.scatterplot(
    data=points,
    x="x",
    y="y",
    ax=ax,
    color=BRAND,
    s=110,
    alpha=0.75,
    edgecolor=PAGE_BG,
    linewidth=0.75,
    zorder=10,
    legend=False,
)

# Vertex labels
label_offset = 0.07
ax.text(0, -label_offset, f"{SAND} (100%)", ha="center", va="top", fontsize=10, fontweight="bold", color=INK)
ax.text(1, -label_offset, f"{SILT} (100%)", ha="center", va="top", fontsize=10, fontweight="bold", color=INK)
ax.text(
    0.5, sqrt3_2 + label_offset, f"{CLAY} (100%)", ha="center", va="bottom", fontsize=10, fontweight="bold", color=INK
)

# Title: {Descriptive Title} · {spec-id} · {language} · {library} · anyplot.ai
ax.set_title(
    "Soil Texture Classification · ternary-basic · python · seaborn · anyplot.ai",
    fontsize=10,
    pad=8,
    color=INK,
    fontweight="medium",
)

# Clean up axes
ax.set_xlim(-0.15, 1.15)
ax.set_ylim(-0.18, 1.0)
ax.set_aspect("equal")
ax.axis("off")

fig.subplots_adjust(left=0.04, right=0.96, top=0.90, bottom=0.06)
plt.savefig(f"plot-{THEME}.png", dpi=400, facecolor=PAGE_BG)  # bbox_inches MUST stay default (None) — see canvas rule

Retrieve this implementation

Runnable source as JSON, for any HTTP client: https://api.anyplot.ai/specs/ternary-basic/seaborn/code. Any spec id and library id listed in llms-full.txt fit the same URL shape; every URL below is complete and callable.

{
  "spec_id": "ternary-basic",
  "language": "python",
  "library": "seaborn",
  "page": "https://anyplot.ai/ternary-basic/python/seaborn",
  "hub": "https://anyplot.ai/ternary-basic",
  "code_json": "https://api.anyplot.ai/specs/ternary-basic/seaborn/code",
  "spec_json": "https://api.anyplot.ai/specs/ternary-basic",
  "render_light_png": "https://storage.googleapis.com/anyplot-images/plots/ternary-basic/python/seaborn/plot-light.png",
  "render_dark_png": "https://storage.googleapis.com/anyplot-images/plots/ternary-basic/python/seaborn/plot-dark.png",
  "quality_score": 82.0,
  "license": "MIT",
  "guide": "https://anyplot.ai/llms.txt"
}

Part of Basic Ternary Plot on anyplot.ai.

Other implementations