{"spec_id":"line-impurity-comparison","library":"muix","language":"javascript","code":"// anyplot.ai\n// line-impurity-comparison: Gini Impurity vs Entropy Comparison\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 88/100 | Updated: 2026-11-08\n\nimport { LineChart } from \"@mui/x-charts/LineChart\";\nimport { ChartsReferenceLine } from \"@mui/x-charts/ChartsReferenceLine\";\nimport { useXScale, useYScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst GINI_LABEL = \"Gini impurity: 2p(1 − p)\";\nconst ENTROPY_LABEL = \"Entropy: −p log₂p − (1 − p) log₂(1 − p)\";\nconst IMPURITY_LABEL = \"Impurity\";\nconst Y_DOMAIN_MAX = 1; // both criteria share the axis 0 to 1\nconst Y_HEAD_SHARE = 0.08; // headroom above 1 so the entropy peak and its label stay inside\n\n// Columns: set these to your data's column names\nconst P = \"Probability of class 1 (p)\"; // role: p\n\n// Data: replace this block with your own records, one object per row\n// 101 evenly spaced probabilities, so p = 0.5 is one of the samples.\nconst data = Array.from({ length: 101 }, (_, i) => ({ [P]: i / 100 }));\n\n// Plot: reads only data and the constants above\nconst rows = [...data].sort((a, b) => a[P] - b[P]);\nconst ps = rows.map((d) => d[P]);\nconst gini = ps.map((p) => 2 * p * (1 - p));\n// 0 · log₂0 is undefined; its limit 0 closes the entropy curve at p = 0 and p = 1.\nconst entropy = ps.map((p) => (p > 0 && p < 1 ? -p * Math.log2(p) - (1 - p) * Math.log2(1 - p) : 0));\n\n// Both curves fall strictly with |p − 0.5|, so the sample nearest 0.5 is the maximum of both.\nconst peakIdx = gini.indexOf(Math.max(...gini));\nconst peakP = ps[peakIdx];\nconst curves = [\n  { id: \"gini\", label: GINI_LABEL, values: gini },\n  { id: \"entropy\", label: ENTROPY_LABEL, values: entropy },\n].map((c, i) => ({ ...c, color: t.palette[i], peak: c.values[peakIdx] }));\nconst step = (ps[ps.length - 1] - ps[0]) / (ps.length - 1);\n\nconst TITLE = \"line-impurity-comparison · javascript · muix · anyplot.ai\";\nconst SUBTITLE = `${ps.length} evaluation points, p = ${ps[0].toFixed(2)} to ${ps[ps.length - 1].toFixed(2)} in steps of ${step.toFixed(2)}`;\nconst HEADER_H = 80;\nconst LEGEND_H = 44;\n\n// Value labels beside the two peak marks, placed in data coordinates\nfunction PeakLabels() {\n  const xScale = useXScale() as (v: number) => number;\n  const yScale = useYScale() as (v: number) => number;\n  return (\n    <g>\n      {curves.map((c) => (\n        <text key={c.id} x={xScale(peakP) + 16} y={yScale(c.peak) - 14} fontSize={15} fontWeight={600} fill={t.ink}>\n          Maximum {c.peak.toFixed(2)}\n        </text>\n      ))}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n\n  return (\n    <div style={{ width, height, display: \"flex\", flexDirection: \"column\" }}>\n      <div style={{ height: HEADER_H, padding: \"16px 40px 0 108px\", boxSizing: \"border-box\" }}>\n        <div style={{ fontSize: 22, fontWeight: 600, color: t.ink, lineHeight: 1.25 }}>{TITLE}</div>\n        <div style={{ fontSize: 15, color: t.inkSoft, marginTop: 6 }}>{SUBTITLE}</div>\n      </div>\n      <LineChart\n        width={width}\n        height={height - HEADER_H - LEGEND_H}\n        skipAnimation\n        grid={{ horizontal: true }}\n        margin={{ top: 12, right: 48, bottom: 16, left: 24 }}\n        xAxis={[\n          {\n            data: ps,\n            scaleType: \"linear\",\n            min: ps[0],\n            max: ps[ps.length - 1],\n            tickNumber: 6,\n            label: P,\n            height: 64,\n            valueFormatter: (v: number) => v.toFixed(2),\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            min: 0,\n            max: Y_DOMAIN_MAX * (1 + Y_HEAD_SHARE),\n            tickNumber: 6,\n            label: IMPURITY_LABEL,\n            width: 76,\n            valueFormatter: (v: number) => v.toFixed(1),\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        series={curves.map((c) => ({\n          id: c.id,\n          data: c.values,\n          label: c.label,\n          color: c.color,\n          curve: \"natural\",\n          area: true,\n          shape: \"circle\",\n          showMark: ({ index }: { index: number }) => index === peakIdx,\n          valueFormatter: (v: number | null) => (v == null ? \"\" : v.toFixed(3)),\n        }))}\n        slotProps={{\n          legend: {\n            direction: \"horizontal\",\n            position: { vertical: \"top\", horizontal: \"center\" },\n            sx: {\n              fontSize: 16,\n              color: t.ink,\n              columnGap: 4,\n              // The peak marks are filled with their series colour, so the legend glyphs are filled too\n              ...Object.fromEntries(\n                curves.map((c) => [`& .MuiChartsLegend-item[data-series=\"${c.id}\"] .MuiChartsLegend-mark path:last-of-type`, { fill: c.color }]),\n              ),\n            },\n          },\n        }}\n        sx={{\n          \"& .MuiLineChart-line\": { strokeWidth: 3.5 },\n          // Gini's fill sits under entropy's: the lone entropy wash between the curves shows where they differ.\n          '& .MuiLineChart-area[data-series=\"gini\"]': { fillOpacity: 0.22 },\n          '& .MuiLineChart-area[data-series=\"entropy\"]': { fillOpacity: 0.16 },\n          \"& .MuiLineChart-mark\": { r: 7, strokeWidth: 2.5, stroke: t.pageBg },\n          ...Object.fromEntries(curves.map((c) => [`& .MuiLineChart-mark[data-series=\"${c.id}\"]`, { fill: c.color }])),\n          \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n          \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n          \"& .MuiChartsGrid-line\": { stroke: t.grid, strokeWidth: 1 },\n        }}\n      >\n        <ChartsReferenceLine\n          x={peakP}\n          label={`Maximum impurity at p = ${peakP.toFixed(2)}`}\n          labelAlign=\"end\"\n          spacing={{ x: 12, y: 14 }}\n          lineStyle={{ stroke: t.inkSoft, strokeDasharray: \"6 4\", strokeWidth: 1.5 }}\n          labelStyle={{ fontSize: 15, fill: t.inkSoft }}\n        />\n        <PeakLabels />\n      </LineChart>\n    </div>\n  );\n}\n"}