{"spec_id":"bar-diverging-likert","library":"muix","language":"javascript","code":"// anyplot.ai\n// bar-diverging-likert: Likert Scale Diverging Bar Chart\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 88/100 | Updated: 2026-11-08\nimport { BarChart } from \"@mui/x-charts/BarChart\";\nimport { ChartsReferenceLine } from \"@mui/x-charts/ChartsReferenceLine\";\nimport { useXScale, useYScale } from \"@mui/x-charts/hooks\";\nimport Box from \"@mui/material/Box\";\nimport Typography from \"@mui/material/Typography\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst TITLE = \"bar-diverging-likert · javascript · muix · anyplot.ai\";\nconst TITLE_H = 84;\nconst LEGEND_H = 48;\nconst X_LABEL = \"Share of responses (%)\";\nconst PAD_SHARE = 0.06; // room beyond the longest half-bar\nconst MIN_LABEL_PX = 38; // a segment narrower than this keeps no percentage label\n// The style guide's muted anchor (not among the tokens) for the neutral level\nconst MUTED = t.theme === \"dark\" ? \"#A8A79F\" : \"#6B6A63\";\nconst STEP_SHARE = 0.45; // the mild levels sit this far from their pole toward the ramp's midpoint\nconst DARK_INK = \"#1A1A17\";\nconst LIGHT_INK = \"#FAF8F1\";\n\n// Columns: set these to your data's column names\nconst QUESTION = \"Survey question\"; // role: question\nconst STRONGLY_DISAGREE = \"Strongly disagree\"; // role: strongly_disagree\nconst DISAGREE = \"Disagree\"; // role: disagree\nconst NEUTRAL = \"Neutral\"; // role: neutral\nconst AGREE = \"Agree\"; // role: agree\nconst STRONGLY_AGREE = \"Strongly agree\"; // role: strongly_agree\n\n// Data: replace this block with your own records, one object per row\n// Employee engagement survey, 5-point Likert scale, percent of responses per level\nconst data = [\n  { [QUESTION]: \"I understand my role's impact\", [STRONGLY_DISAGREE]: 2, [DISAGREE]: 5, [NEUTRAL]: 8, [AGREE]: 45, [STRONGLY_AGREE]: 40 },\n  { [QUESTION]: \"I receive regular recognition\", [STRONGLY_DISAGREE]: 8, [DISAGREE]: 17, [NEUTRAL]: 20, [AGREE]: 35, [STRONGLY_AGREE]: 20 },\n  { [QUESTION]: \"I have growth opportunities\", [STRONGLY_DISAGREE]: 10, [DISAGREE]: 22, [NEUTRAL]: 23, [AGREE]: 30, [STRONGLY_AGREE]: 15 },\n  { [QUESTION]: \"My manager gives useful feedback\", [STRONGLY_DISAGREE]: 5, [DISAGREE]: 12, [NEUTRAL]: 18, [AGREE]: 40, [STRONGLY_AGREE]: 25 },\n  { [QUESTION]: \"I can share ideas openly\", [STRONGLY_DISAGREE]: 4, [DISAGREE]: 11, [NEUTRAL]: 15, [AGREE]: 42, [STRONGLY_AGREE]: 28 },\n  { [QUESTION]: \"Changes are communicated well\", [STRONGLY_DISAGREE]: 12, [DISAGREE]: 25, [NEUTRAL]: 20, [AGREE]: 28, [STRONGLY_AGREE]: 15 },\n  { [QUESTION]: \"My workload is manageable\", [STRONGLY_DISAGREE]: 18, [DISAGREE]: 27, [NEUTRAL]: 15, [AGREE]: 28, [STRONGLY_AGREE]: 12 },\n  { [QUESTION]: \"I'd recommend this company\", [STRONGLY_DISAGREE]: 3, [DISAGREE]: 7, [NEUTRAL]: 12, [AGREE]: 38, [STRONGLY_AGREE]: 40 },\n];\n\n// Plot: reads only data and the constants above\nconst LEVELS = [STRONGLY_DISAGREE, DISAGREE, NEUTRAL, AGREE, STRONGLY_AGREE]; // scale order\n\n// Most net agreement first: (agree + strongly agree) minus (disagree + strongly disagree)\nconst ranked = data\n  .map((d) => ({ row: d, net: d[AGREE] + d[STRONGLY_AGREE] - d[DISAGREE] - d[STRONGLY_DISAGREE] }))\n  .sort((a, b) => b.net - a.net);\nconst rows = ranked.map((r) => r.row);\nconst nets = ranked.map((r) => r.net);\nconst questions = rows.map((d) => d[QUESTION]);\n\n// Ordered levels take steps of the diverging Imprint ramp: the poles at its ends,\n// the mild levels part-way toward its midpoint, neutral in the muted anchor\nconst levelRgb = [\n  [t.div[0], t.div[0], 0],\n  [t.div[0], t.div[1], STEP_SHARE],\n  [MUTED, MUTED, 0],\n  [t.div[2], t.div[1], STEP_SHARE],\n  [t.div[2], t.div[2], 0],\n].map(([from, to, share]) =>\n  [1, 3, 5].map((i) =>\n    Math.round(parseInt(String(from).slice(i, i + 2), 16) * (1 - Number(share)) + parseInt(String(to).slice(i, i + 2), 16) * Number(share)),\n  ),\n);\nconst LEVEL_COLORS = levelRgb.map(([r, g, b]) => `rgb(${r}, ${g}, ${b})`);\n\n// Label ink per level: whichever fixed ink contrasts more with the segment's fill\nconst LEVEL_INKS = levelRgb.map((rgb) => {\n  const [R, G, B] = rgb.map((v) => (v / 255 <= 0.03928 ? v / 255 / 12.92 : ((v / 255 + 0.055) / 1.055) ** 2.4));\n  const lum = 0.2126 * R + 0.7152 * G + 0.0722 * B;\n  return (lum + 0.05) / 0.0603 >= 0.985 / (lum + 0.05) ? DARK_INK : LIGHT_INK;\n});\n\n// Diverging stack: neutral split evenly across zero, disagreement stacked left and\n// agreement right; within each sign the first series sits next to the midline\nconst SEGMENTS = [\n  { id: \"neutral-left\", level: 2, sign: -1, share: 0.5 },\n  { id: \"disagree\", level: 1, sign: -1, share: 1 },\n  { id: \"strongly-disagree\", level: 0, sign: -1, share: 1 },\n  { id: \"neutral-right\", level: 2, sign: 1, share: 0.5 },\n  { id: \"agree\", level: 3, sign: 1, share: 1 },\n  { id: \"strongly-agree\", level: 4, sign: 1, share: 1 },\n];\n\nconst reach =\n  Math.max(\n    ...rows.map((d) => d[STRONGLY_DISAGREE] + d[DISAGREE] + d[NEUTRAL] / 2),\n    ...rows.map((d) => d[AGREE] + d[STRONGLY_AGREE] + d[NEUTRAL] / 2),\n  ) *\n    (1 + PAD_SHARE) || 1;\nconst halfStep = 10 ** Math.floor(Math.log10(reach)) / 2;\nconst limit = Math.ceil(reach / halfStep) * halfStep;\n\nconst fmtSigned = (v: number) => `${v > 0 ? \"+\" : \"\"}${v}`;\nconst SUBTITLE = `${rows.length} questions, sorted by net agreement (${fmtSigned(Math.max(...nets))} to ${fmtSigned(Math.min(...nets))} points) · neutral split across the midline`;\n\n// The neutral share is labelled once, in full, on the midline it straddles; a halo\n// in the segment's own fill breaks the midline behind the text\nfunction NeutralLabels() {\n  const xScale = useXScale(\"share\");\n  const yScale = useYScale();\n  const bw = yScale.bandwidth();\n  return (\n    <g>\n      {rows.map((d) => {\n        const share = d[NEUTRAL];\n        if (share == null || Math.abs(xScale(share / 2) - xScale(-share / 2)) < MIN_LABEL_PX) return null;\n        return (\n          <text\n            key={d[QUESTION]}\n            x={xScale(0)}\n            y={yScale(d[QUESTION]) + bw / 2}\n            textAnchor=\"middle\"\n            dominantBaseline=\"central\"\n            fontSize={15}\n            fontWeight={600}\n            fill={LEVEL_INKS[2]}\n            stroke={LEVEL_COLORS[2]}\n            strokeWidth={5}\n            paintOrder=\"stroke\"\n          >\n            {`${share}%`}\n          </text>\n        );\n      })}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n\n  return (\n    <Box sx={{ width, height, bgcolor: t.pageBg, display: \"flex\", flexDirection: \"column\" }}>\n      <Box sx={{ height: TITLE_H, px: \"40px\", pt: \"18px\", boxSizing: \"border-box\" }}>\n        <Typography sx={{ color: t.ink, fontSize: \"22px\", fontWeight: 600, lineHeight: 1.2 }}>\n          {TITLE}\n        </Typography>\n        <Typography sx={{ color: t.inkSoft, fontSize: \"15px\", lineHeight: 1.2, mt: \"8px\" }}>\n          {SUBTITLE}\n        </Typography>\n      </Box>\n      <BarChart\n        width={width}\n        height={height - TITLE_H - LEGEND_H}\n        layout=\"horizontal\"\n        skipAnimation\n        hideLegend\n        grid={{ vertical: true }}\n        series={SEGMENTS.map((seg) => ({\n          id: seg.id,\n          stack: \"likert\",\n          label: LEVELS[seg.level],\n          color: LEVEL_COLORS[seg.level],\n          data: rows.map((d) => seg.sign * d[LEVELS[seg.level]] * seg.share),\n          valueFormatter: (_v: number | null, { dataIndex }: { dataIndex: number }) =>\n            `${rows[dataIndex][LEVELS[seg.level]]}%`,\n          // the neutral halves carry no label of their own: NeutralLabels draws it on the midline\n          barLabel: (item: { dataIndex: number }, ctx: { bar: { width: number } }) =>\n            seg.level === 2 || ctx.bar.width < MIN_LABEL_PX ? null : `${rows[item.dataIndex][LEVELS[seg.level]]}%`,\n        }))}\n        xAxis={[\n          {\n            id: \"share\",\n            min: -limit,\n            max: limit,\n            label: X_LABEL,\n            height: 64,\n            valueFormatter: (v: number) => `${Math.abs(v)}`,\n            tickLabelStyle: { fontSize: 15, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            scaleType: \"band\",\n            data: questions,\n            width: 290,\n            categoryGapRatio: 0.3,\n            disableTicks: true,\n            tickLabelStyle: { fontSize: 15, fill: t.ink },\n          },\n        ]}\n        margin={{ top: 16, right: 48, bottom: 8, left: 24 }}\n        sx={{\n          \"& .MuiBarChart-label\": { fontSize: 15, fontWeight: 600 },\n          ...Object.fromEntries(\n            SEGMENTS.map((seg) => [`& [data-series=\"${seg.id}\"] .MuiBarChart-label`, { fill: LEVEL_INKS[seg.level] }]),\n          ),\n          \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n          \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n          \"& .MuiChartsGrid-line\": { stroke: t.grid, strokeWidth: 1 },\n        }}\n      >\n        <ChartsReferenceLine x={0} axisId=\"share\" lineStyle={{ stroke: t.ink, strokeWidth: 2 }} />\n        <NeutralLabels />\n      </BarChart>\n      <Box sx={{ height: LEGEND_H, display: \"flex\", alignItems: \"center\", justifyContent: \"center\", gap: \"28px\" }}>\n        {LEVELS.map((level, i) => (\n          <Box key={level} sx={{ display: \"flex\", alignItems: \"center\", gap: \"8px\" }}>\n            <Box sx={{ width: 16, height: 16, borderRadius: \"3px\", bgcolor: LEVEL_COLORS[i] }} />\n            <Typography sx={{ fontSize: 15, color: t.ink }}>{level}</Typography>\n          </Box>\n        ))}\n      </Box>\n    </Box>\n  );\n}\n"}