{"spec_id":"ternary-density","library":"muix","language":"javascript","code":"// anyplot.ai\n// ternary-density: Ternary Density Plot\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 86/100 | Updated: 2026-10-23\n//# anyplot-orientation: square\n\nimport { ChartsContainer } from \"@mui/x-charts/ChartsContainer\";\nimport { ScatterPlot } from \"@mui/x-charts/ScatterChart\";\nimport { ChartsTooltip } from \"@mui/x-charts/ChartsTooltip\";\nimport { useXScale, useYScale, useDrawingArea } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Columns: set these to your data's column names\nconst COMPONENT_A = \"Sand\"; // role: component_a\nconst COMPONENT_B = \"Silt\"; // role: component_b\nconst COMPONENT_C = \"Clay\"; // role: component_c\n\n// Data: replace this block with your own records, one object per row\nconst data = (() => {\n  let seed = 20260902 >>> 0;\n  const rand = () => {\n    seed = (1664525 * seed + 1013904223) >>> 0;\n    return seed / 4294967296;\n  };\n  const erlang = (k: number) => {\n    let s = 0;\n    for (let i = 0; i < k; i++) s += -Math.log(rand() || 1e-9);\n    return s;\n  };\n\n  const clusters = [\n    { n: 190, shape: [19, 4, 3] }, // sandy soils\n    { n: 220, shape: [8, 8, 4] }, // loamy soils\n    { n: 170, shape: [4, 5, 11] }, // clay-rich soils\n  ];\n\n  const rows: {\n    [COMPONENT_A]: number;\n    [COMPONENT_B]: number;\n    [COMPONENT_C]: number;\n  }[] = [];\n\n  for (const cluster of clusters) {\n    for (let i = 0; i < cluster.n; i++) {\n      const gA = erlang(cluster.shape[0]);\n      const gB = erlang(cluster.shape[1]);\n      const gC = erlang(cluster.shape[2]);\n      const total = gA + gB + gC;\n      rows.push({\n        [COMPONENT_A]: (gA / total) * 100,\n        [COMPONENT_B]: (gB / total) * 100,\n        [COMPONENT_C]: (gC / total) * 100,\n      });\n    }\n  }\n  return rows;\n})();\n\n// Plot: reads only data and the constants above\nconst SIZE = window.ANYPLOT_SIZE;\nconst TITLE =\n  \"Soil Texture Density · ternary-density · javascript · muix · anyplot.ai\";\nconst FONT =\n  '-apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, Helvetica, Arial, sans-serif';\n\nconst SQRT3_2 = Math.sqrt(3) / 2;\nfunction toXY(a: number, b: number, c: number) {\n  const total = a + b + c;\n  const aN = a / total;\n  const cN = c / total;\n  return { x: cN + aN / 2, y: SQRT3_2 * aN };\n}\nconst VERTEX_TOP = toXY(1, 0, 0);\nconst VERTEX_LEFT = toXY(0, 1, 0);\nconst VERTEX_RIGHT = toXY(0, 0, 1);\n\nconst samplePoints = data.map((d) =>\n  toXY(d[COMPONENT_A], d[COMPONENT_B], d[COMPONENT_C]),\n);\n\nconst GRID_N = 46;\nconst BANDWIDTH = 0.055;\nconst TWO_H2 = 2 * BANDWIDTH * BANDWIDTH;\n\nconst densityPoints: {\n  x: number;\n  y: number;\n  z: number;\n  rawZ: number;\n  id: string;\n}[] = [];\nconst aPct: number[] = [];\nconst bPct: number[] = [];\nconst cPct: number[] = [];\nlet maxDensity = 0;\nfor (let i = 0; i <= GRID_N; i++) {\n  for (let j = 0; j <= GRID_N - i; j++) {\n    const k = GRID_N - i - j;\n    const { x, y } = toXY(i, j, k);\n    let density = 0;\n    for (let s = 0; s < samplePoints.length; s++) {\n      const dx = x - samplePoints[s].x;\n      const dy = y - samplePoints[s].y;\n      density += Math.exp(-(dx * dx + dy * dy) / TWO_H2);\n    }\n    density /= samplePoints.length;\n    if (density > maxDensity) maxDensity = density;\n    densityPoints.push({ x, y, z: density, rawZ: density, id: `cell-${i}-${j}` });\n    aPct.push(Math.round((i / GRID_N) * 100));\n    bPct.push(Math.round((j / GRID_N) * 100));\n    cPct.push(Math.round((k / GRID_N) * 100));\n  }\n}\n\n// gamma < 1 lifts the weaker loamy and clay-rich modes off the low-density floor\nconst COLOR_GAMMA = 0.8;\nfor (const p of densityPoints) {\n  p.z = Math.pow(p.rawZ / maxDensity, COLOR_GAMMA) * maxDensity;\n}\n\nconst GRID_LEVELS = [0.2, 0.4, 0.6, 0.8];\nconst GRID_SEGMENTS: { x: number; y: number }[][] = [];\nfor (const f of GRID_LEVELS) {\n  GRID_SEGMENTS.push([toXY(f, 1 - f, 0), toXY(f, 0, 1 - f)]);\n  GRID_SEGMENTS.push([toXY(1 - f, f, 0), toXY(0, f, 1 - f)]);\n  GRID_SEGMENTS.push([toXY(1 - f, 0, f), toXY(0, 1 - f, f)]);\n}\nconst TICK_LEVELS = [20, 40, 60, 80];\nconst LEFT_TICKS = TICK_LEVELS.map((pct) => ({\n  pct,\n  pos: toXY(pct / 100, 1 - pct / 100, 0),\n}));\nconst BOTTOM_TICKS = TICK_LEVELS.map((pct) => ({\n  pct,\n  pos: toXY(0, pct / 100, 1 - pct / 100),\n}));\nconst RIGHT_TICKS = TICK_LEVELS.map((pct) => ({\n  pct,\n  pos: toXY(1 - pct / 100, 0, pct / 100),\n}));\n\nconst X_MIN = -0.108;\nconst X_MAX = 1.108;\nconst Y_MIN = -0.26;\nconst Y_MAX = 0.956;\n\nfunction TriangleGrid() {\n  const xs = useXScale();\n  const ys = useYScale();\n  return (\n    <g>\n      {GRID_SEGMENTS.map((seg, i) => (\n        <line\n          key={i}\n          x1={xs(seg[0].x)}\n          y1={ys(seg[0].y)}\n          x2={xs(seg[1].x)}\n          y2={ys(seg[1].y)}\n          stroke={t.grid}\n          strokeWidth={1.5}\n          strokeDasharray=\"6 5\"\n        />\n      ))}\n      <path\n        d={`M${xs(VERTEX_TOP.x)} ${ys(VERTEX_TOP.y)} L${xs(VERTEX_LEFT.x)} ${ys(VERTEX_LEFT.y)} L${xs(VERTEX_RIGHT.x)} ${ys(VERTEX_RIGHT.y)} Z`}\n        fill=\"none\"\n        stroke={t.inkSoft}\n        strokeWidth={2.5}\n        strokeLinejoin=\"round\"\n      />\n    </g>\n  );\n}\n\nfunction DensityLayer() {\n  const xs = useXScale();\n  const ys = useYScale();\n  const clipD = `M${xs(VERTEX_TOP.x)} ${ys(VERTEX_TOP.y)} L${xs(VERTEX_LEFT.x)} ${ys(VERTEX_LEFT.y)} L${xs(VERTEX_RIGHT.x)} ${ys(VERTEX_RIGHT.y)} Z`;\n  return (\n    <>\n      <defs>\n        <clipPath id=\"ternaryTriangleClip\">\n          <path d={clipD} />\n        </clipPath>\n      </defs>\n      <g clipPath=\"url(#ternaryTriangleClip)\">\n        <ScatterPlot />\n      </g>\n    </>\n  );\n}\n\nfunction GridOverlay() {\n  const xs = useXScale();\n  const ys = useYScale();\n  return (\n    <g>\n      {GRID_SEGMENTS.map((seg, i) => (\n        <line\n          key={`halo-${i}`}\n          x1={xs(seg[0].x)}\n          y1={ys(seg[0].y)}\n          x2={xs(seg[1].x)}\n          y2={ys(seg[1].y)}\n          stroke={t.pageBg}\n          strokeWidth={4}\n          strokeOpacity={0.6}\n          strokeDasharray=\"6 5\"\n        />\n      ))}\n      {GRID_SEGMENTS.map((seg, i) => (\n        <line\n          key={`line-${i}`}\n          x1={xs(seg[0].x)}\n          y1={ys(seg[0].y)}\n          x2={xs(seg[1].x)}\n          y2={ys(seg[1].y)}\n          stroke={t.grid}\n          strokeWidth={1.5}\n          strokeDasharray=\"6 5\"\n        />\n      ))}\n    </g>\n  );\n}\n\nfunction EdgeTicks() {\n  const xs = useXScale();\n  const ys = useYScale();\n  const label = (\n    tick: { pct: number; pos: { x: number; y: number } },\n    dx: number,\n    dy: number,\n    anchor: \"start\" | \"middle\" | \"end\",\n  ) => (\n    <text\n      key={`${dx}-${dy}-${tick.pct}`}\n      x={xs(tick.pos.x)! + dx}\n      y={ys(tick.pos.y)! + dy}\n      textAnchor={anchor}\n      dominantBaseline=\"middle\"\n      fontFamily={FONT}\n      fontSize={16}\n      fill={t.inkSoft}\n    >\n      {tick.pct}%\n    </text>\n  );\n  return (\n    <g>\n      {LEFT_TICKS.map((tk) => label(tk, -16, 0, \"end\"))}\n      {BOTTOM_TICKS.map((tk) => label(tk, 0, 24, \"middle\"))}\n      {RIGHT_TICKS.map((tk) => label(tk, 16, 0, \"start\"))}\n    </g>\n  );\n}\n\n// Names the component each edge scale measures; the arrow points toward 100 %\nfunction EdgeTitles() {\n  const xs = useXScale();\n  const ys = useYScale();\n  const mid = (p: { x: number; y: number }, q: { x: number; y: number }) => ({\n    x: (xs(p.x)! + xs(q.x)!) / 2,\n    y: (ys(p.y)! + ys(q.y)!) / 2,\n  });\n  const left = mid(VERTEX_LEFT, VERTEX_TOP);\n  const right = mid(VERTEX_RIGHT, VERTEX_TOP);\n  const bottom = mid(VERTEX_LEFT, VERTEX_RIGHT);\n  const OFFSET = 84;\n  const titles = [\n    {\n      x: left.x - OFFSET * SQRT3_2,\n      y: left.y - OFFSET / 2,\n      angle: -60,\n      text: `${COMPONENT_A} (%) →`,\n    },\n    {\n      x: right.x + OFFSET * SQRT3_2,\n      y: right.y - OFFSET / 2,\n      angle: 60,\n      text: `${COMPONENT_C} (%) →`,\n    },\n    { x: bottom.x, y: bottom.y + 62, angle: 0, text: `← ${COMPONENT_B} (%)` },\n  ];\n  return (\n    <g fontFamily={FONT} fontSize={18} fontWeight={600} fill={t.inkSoft}>\n      {titles.map((tt) => (\n        <text\n          key={tt.text}\n          x={tt.x}\n          y={tt.y}\n          textAnchor=\"middle\"\n          dominantBaseline=\"middle\"\n          transform={`rotate(${tt.angle} ${tt.x} ${tt.y})`}\n        >\n          {tt.text}\n        </text>\n      ))}\n    </g>\n  );\n}\n\nfunction VertexLabels() {\n  const xs = useXScale();\n  const ys = useYScale();\n  return (\n    <g fontFamily={FONT} fontSize={22} fontWeight={700} fill={t.ink}>\n      <text\n        x={xs(VERTEX_TOP.x)}\n        y={ys(VERTEX_TOP.y)! - 22}\n        textAnchor=\"middle\"\n        dominantBaseline=\"baseline\"\n      >\n        {COMPONENT_A}\n      </text>\n      <text\n        x={xs(VERTEX_LEFT.x)}\n        y={ys(VERTEX_LEFT.y)! + 30}\n        textAnchor=\"middle\"\n        dominantBaseline=\"hanging\"\n      >\n        {COMPONENT_B}\n      </text>\n      <text\n        x={xs(VERTEX_RIGHT.x)}\n        y={ys(VERTEX_RIGHT.y)! + 30}\n        textAnchor=\"middle\"\n        dominantBaseline=\"hanging\"\n      >\n        {COMPONENT_C}\n      </text>\n    </g>\n  );\n}\n\nfunction DensityLegend() {\n  const { left, top, width, height } = useDrawingArea();\n  const barWidth = Math.min(380, width * 0.36);\n  const barHeight = 20;\n  const cx = left + width / 2;\n  const barY = top + height - 92;\n  const barX = cx - barWidth / 2;\n  return (\n    <g fontFamily={FONT}>\n      <defs>\n        <linearGradient id=\"ternaryDensityGradient\" x1=\"0\" x2=\"1\" y1=\"0\" y2=\"0\">\n          <stop offset=\"0%\" stopColor={t.seq[0]} />\n          <stop offset=\"100%\" stopColor={t.seq[1]} />\n        </linearGradient>\n      </defs>\n      <text\n        x={cx}\n        y={barY - 14}\n        textAnchor=\"middle\"\n        fontSize={15}\n        fill={t.inkSoft}\n      >\n        Relative sample density\n      </text>\n      <rect\n        x={barX}\n        y={barY}\n        width={barWidth}\n        height={barHeight}\n        rx={4}\n        fill=\"url(#ternaryDensityGradient)\"\n        stroke={t.ink}\n        strokeOpacity={0.15}\n      />\n      <text\n        x={barX}\n        y={barY + barHeight + 20}\n        textAnchor=\"start\"\n        fontSize={16}\n        fill={t.inkSoft}\n      >\n        Low\n      </text>\n      <text\n        x={barX + barWidth}\n        y={barY + barHeight + 20}\n        textAnchor=\"end\"\n        fontSize={16}\n        fill={t.inkSoft}\n      >\n        High\n      </text>\n    </g>\n  );\n}\n\nfunction Title() {\n  const xs = useXScale();\n  const ys = useYScale();\n  const n = TITLE.length;\n  const ratio = n > 67 ? 67 / n : 1.0;\n  const fontSize = Math.max(15, Math.round(22 * ratio));\n  return (\n    <text\n      x={xs((X_MIN + X_MAX) / 2)}\n      y={ys(Y_MAX)! + 4}\n      textAnchor=\"middle\"\n      dominantBaseline=\"hanging\"\n      fontFamily={FONT}\n      fontSize={fontSize}\n      fontWeight={600}\n      fill={t.ink}\n    >\n      {TITLE}\n    </text>\n  );\n}\n\nexport default function Chart() {\n  return (\n    <ChartsContainer\n      width={SIZE.width}\n      height={SIZE.height}\n      margin={{ top: 24, right: 24, bottom: 24, left: 24 }}\n      series={[\n        {\n          type: \"scatter\",\n          label: \"Sample density\",\n          color: t.seq[0],\n          markerSize: 13,\n          data: densityPoints,\n          valueFormatter: (_value: any, ctx: any) =>\n            `${COMPONENT_A} ${aPct[ctx.dataIndex]}% · ${COMPONENT_B} ${bPct[ctx.dataIndex]}% · ${COMPONENT_C} ${cPct[ctx.dataIndex]}% — ${Math.round((densityPoints[ctx.dataIndex].rawZ / maxDensity) * 100)}% of peak density`,\n        },\n      ]}\n      xAxis={[{ scaleType: \"linear\", min: X_MIN, max: X_MAX, position: \"none\" }]}\n      yAxis={[{ scaleType: \"linear\", min: Y_MIN, max: Y_MAX, position: \"none\" }]}\n      zAxis={[\n        {\n          id: \"density\",\n          min: 0,\n          max: maxDensity,\n          colorMap: { type: \"continuous\", color: [t.seq[0], t.seq[1]] },\n        },\n      ]}\n      skipAnimation\n    >\n      <TriangleGrid />\n      <DensityLayer />\n      <GridOverlay />\n      <EdgeTicks />\n      <EdgeTitles />\n      <VertexLabels />\n      <DensityLegend />\n      <Title />\n      <ChartsTooltip trigger=\"item\" />\n    </ChartsContainer>\n  );\n}\n"}