{"spec_id":"bar-tornado-sensitivity","library":"muix","language":"javascript","code":"// anyplot.ai\n// bar-tornado-sensitivity: Tornado Diagram for Sensitivity Analysis\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 87/100 | Updated: 2026-11-08\nimport { ChartsContainer } from \"@mui/x-charts/ChartsContainer\";\nimport { ChartsXAxis } from \"@mui/x-charts/ChartsXAxis\";\nimport { ChartsYAxis } from \"@mui/x-charts/ChartsYAxis\";\nimport { ChartsGrid } from \"@mui/x-charts/ChartsGrid\";\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 = \"NPV Sensitivity Analysis · bar-tornado-sensitivity · javascript · muix · anyplot.ai\";\nconst TITLE_H = 84;\nconst LEGEND_H = 40;\nconst PAD_SHARE = 0.12; // room beyond the outermost bar ends for their value labels\n// The two scenarios of a one-way sensitivity analysis, coloured by scenario on every bar\nconst LOW_LABEL = \"Low input\";\nconst HIGH_LABEL = \"High input\";\nconst BASE_LABEL = \"Base case\";\nconst LOW_COLOR = t.palette[0];\nconst HIGH_COLOR = t.palette[1];\n\n// Columns: set these to your data's column names\nconst PARAMETER = \"Input parameter\"; // role: parameter\nconst LOW_VALUE = \"NPV at low input (USD)\"; // role: low_value\nconst HIGH_VALUE = \"NPV at high input (USD)\"; // role: high_value\nconst BASE_VALUE = \"Net present value (USD)\"; // role: base_value\n\n// Data: replace this block with your own records, one object per row\n// One-way sensitivity of a project's NPV: each assumption moves between its low and\n// high scenario while every other one stays at the base case\nconst data = [\n  { [PARAMETER]: \"Revenue Growth Rate\", [LOW_VALUE]: 1750000, [HIGH_VALUE]: 3150000, [BASE_VALUE]: 2400000 },\n  { [PARAMETER]: \"Discount Rate\", [LOW_VALUE]: 3000000, [HIGH_VALUE]: 1900000, [BASE_VALUE]: 2400000 },\n  { [PARAMETER]: \"Terminal Growth Rate\", [LOW_VALUE]: 2050000, [HIGH_VALUE]: 2900000, [BASE_VALUE]: 2400000 },\n  { [PARAMETER]: \"Operating Margin\", [LOW_VALUE]: 2000000, [HIGH_VALUE]: 2750000, [BASE_VALUE]: 2400000 },\n  { [PARAMETER]: \"Exit Multiple\", [LOW_VALUE]: 2100000, [HIGH_VALUE]: 2700000, [BASE_VALUE]: 2400000 },\n  { [PARAMETER]: \"Capital Expenditure\", [LOW_VALUE]: 2650000, [HIGH_VALUE]: 2150000, [BASE_VALUE]: 2400000 },\n  { [PARAMETER]: \"Tax Rate\", [LOW_VALUE]: 2550000, [HIGH_VALUE]: 2200000, [BASE_VALUE]: 2400000 },\n  { [PARAMETER]: \"Working Capital Change\", [LOW_VALUE]: 2500000, [HIGH_VALUE]: 2300000, [BASE_VALUE]: 2400000 },\n];\n\n// Plot: reads only data and the constants above\nconst base = data.find((d) => d[BASE_VALUE] != null)?.[BASE_VALUE] ?? 0;\n// Widest swing first, so the bars taper into the tornado shape; a missing end counts as the base case\nconst rows = data\n  .filter((d) => d[LOW_VALUE] != null || d[HIGH_VALUE] != null)\n  .sort(\n    (a, b) =>\n      Math.abs((b[HIGH_VALUE] ?? base) - (b[LOW_VALUE] ?? base)) -\n      Math.abs((a[HIGH_VALUE] ?? base) - (a[LOW_VALUE] ?? base)),\n  );\nconst parameters = rows.map((d) => d[PARAMETER]);\n\nconst fmt = new Intl.NumberFormat(\"en-US\", { notation: \"compact\", maximumFractionDigits: 2 }).format;\n\n// Value axis spans every bar end and the base case, padded for the end labels\nconst ends = rows.flatMap((d) => [d[LOW_VALUE], d[HIGH_VALUE]]).filter((v) => v != null);\nconst lo = Math.min(base, ...ends);\nconst hi = Math.max(base, ...ends);\nconst pad = (hi - lo || Math.abs(base) || 1) * PAD_SHARE;\n\nconst widest = rows[0];\nconst SUBTITLE = `${rows.length} parameters varied one at a time around a ${BASE_LABEL.toLowerCase()} of ${fmt(base)} · widest swing: ${widest[PARAMETER]}, ${fmt(widest[LOW_VALUE] ?? base)} to ${fmt(widest[HIGH_VALUE] ?? base)}`;\n\n// Custom layer: each bar runs from the base case to its scenario result; when both\n// results fall on one side, the longer bar is drawn first so the shorter stays visible\nfunction TornadoBars() {\n  const xScale = useXScale(\"npv\");\n  const yScale = useYScale(\"parameter\");\n  const bw = yScale.bandwidth();\n  const x0 = xScale(base);\n\n  return (\n    <g>\n      {rows.map((d) => {\n        const y = yScale(d[PARAMETER]);\n        const scenarios = [\n          { key: \"low\", value: d[LOW_VALUE], color: LOW_COLOR },\n          { key: \"high\", value: d[HIGH_VALUE], color: HIGH_COLOR },\n        ]\n          .filter((s) => s.value != null)\n          .sort((a, b) => Math.abs(b.value - base) - Math.abs(a.value - base));\n        return (\n          <g key={d[PARAMETER]}>\n            {scenarios.map((s) => {\n              const xe = xScale(s.value);\n              const left = s.value < base;\n              return (\n                <g key={s.key}>\n                  <rect x={Math.min(x0, xe)} y={y} width={Math.abs(xe - x0)} height={bw} rx={3} fill={s.color} />\n                  <text\n                    x={xe + (left ? -8 : 8)}\n                    y={y + bw / 2}\n                    textAnchor={left ? \"end\" : \"start\"}\n                    dominantBaseline=\"central\"\n                    fontSize={15}\n                    fontWeight={500}\n                    fill={t.ink}\n                  >\n                    {fmt(s.value)}\n                  </text>\n                </g>\n              );\n            })}\n          </g>\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      <Box sx={{ height: LEGEND_H, display: \"flex\", alignItems: \"center\", justifyContent: \"center\", gap: \"28px\" }}>\n        {[\n          { label: LOW_LABEL, color: LOW_COLOR },\n          { label: HIGH_LABEL, color: HIGH_COLOR },\n        ].map((s) => (\n          <Box key={s.label} sx={{ display: \"flex\", alignItems: \"center\", gap: \"8px\" }}>\n            <Box sx={{ width: 16, height: 16, borderRadius: \"3px\", bgcolor: s.color }} />\n            <Typography sx={{ fontSize: 15, color: t.ink }}>{s.label}</Typography>\n          </Box>\n        ))}\n        <Box sx={{ display: \"flex\", alignItems: \"center\", gap: \"8px\" }}>\n          <Box sx={{ width: 24, height: 0, borderTop: `2px dashed ${t.ink}` }} />\n          <Typography sx={{ fontSize: 15, color: t.ink }}>{`${BASE_LABEL}: ${fmt(base)}`}</Typography>\n        </Box>\n      </Box>\n      <ChartsContainer\n        width={width}\n        height={height - TITLE_H - LEGEND_H}\n        skipAnimation\n        series={[]}\n        xAxis={[\n          {\n            id: \"npv\",\n            scaleType: \"linear\",\n            min: lo - pad,\n            max: hi + pad,\n            label: BASE_VALUE,\n            height: 64,\n            tickNumber: 8,\n            valueFormatter: fmt,\n            tickLabelStyle: { fontSize: 15, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            id: \"parameter\",\n            scaleType: \"band\",\n            data: parameters,\n            label: PARAMETER,\n            width: 250,\n            categoryGapRatio: 0.3,\n            disableTicks: true,\n            tickLabelStyle: { fontSize: 15, fill: t.ink },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        margin={{ top: 12, right: 48, bottom: 8, left: 24 }}\n        sx={{\n          \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n          \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n          \"& .MuiChartsGrid-line\": { stroke: t.grid, strokeWidth: 1 },\n        }}\n      >\n        <ChartsGrid vertical />\n        <TornadoBars />\n        <ChartsReferenceLine\n          x={base}\n          axisId=\"npv\"\n          lineStyle={{ stroke: t.ink, strokeWidth: 2, strokeDasharray: \"6 4\" }}\n        />\n        <ChartsXAxis axisId=\"npv\" />\n        <ChartsYAxis axisId=\"parameter\" />\n      </ChartsContainer>\n    </Box>\n  );\n}\n"}