{"spec_id":"histogram-epidemic","library":"muix","language":"javascript","code":"// anyplot.ai\n// histogram-epidemic: Epidemic Curve (Epi Curve)\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 87/100 | Updated: 2026-10-24\nimport { ChartsContainer } from \"@mui/x-charts/ChartsContainer\";\nimport { BarPlot } from \"@mui/x-charts/BarChart\";\nimport { LinePlot } from \"@mui/x-charts/LineChart\";\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 Box from \"@mui/material/Box\";\nimport Typography from \"@mui/material/Typography\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst FONT = \"system-ui, -apple-system, sans-serif\";\nconst TITLE = \"histogram-epidemic · javascript · muix · anyplot.ai\";\nconst Y_HEADROOM_RATIO = 0.14;\nconst MONTH_ABBR = [\n  \"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\",\n  \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\",\n];\n\n// Columns: set these to your data's column names\nconst ONSET_DATE = \"Symptom Onset Date\"; // role: onset_date\nconst CASE_TYPE = \"Case Classification\"; // role: case_type\nconst DAILY_CASES = \"Daily New Cases\"; // role: case_count\nconst EVENT_LABEL = \"Intervention Event\"; // role: events\n\n// Data: replace this block with your own records\ntype EpiRow = {\n  [ONSET_DATE]: string;\n  [CASE_TYPE]: string;\n  [DAILY_CASES]: number;\n  [EVENT_LABEL]: string;\n};\n\nconst data: EpiRow[] = [];\nlet seed = 42;\nconst dayCount = 63;\nconst startMs = Date.UTC(2024, 0, 1);\nconst eventByDayIndex: Record<number, string> = {\n  20: \"Lockdown start\",\n  45: \"Vaccination campaign\",\n};\n\nconst rawDailyTotals: number[] = [];\nfor (let day = 0; day < dayCount; day++) {\n  const z1 = (day - 14) / 5;\n  const wave1 = 46 * Math.exp(-0.5 * z1 * z1);\n  const z2 = (day - 39) / 8;\n  const wave2 = 30 * Math.exp(-0.5 * z2 * z2);\n  seed = (seed * 1103515245 + 12345) % 2147483648;\n  const noise = (seed / 2147483648 - 0.5) * 6;\n  rawDailyTotals.push(Math.max(0, Math.round(wave1 + wave2 + noise)));\n}\n\nconst rawConfirmed: number[] = [];\nfor (let day = 0; day < dayCount; day++) {\n  seed = (seed * 1103515245 + 12345) % 2147483648;\n  const frac = 0.55 + (seed / 2147483648) * 0.1;\n  rawConfirmed.push(Math.round(rawDailyTotals[day] * frac));\n}\n\nconst rawProbable: number[] = [];\nfor (let day = 0; day < dayCount; day++) {\n  seed = (seed * 1103515245 + 12345) % 2147483648;\n  const frac = 0.55 + (seed / 2147483648) * 0.1;\n  rawProbable.push(\n    Math.round((rawDailyTotals[day] - rawConfirmed[day]) * frac),\n  );\n}\n\nfor (let day = 0; day < dayCount; day++) {\n  const isoDate = new Date(startMs + day * 86400000).toISOString().slice(0, 10);\n  const ev = eventByDayIndex[day] ?? \"\";\n  const conf = rawConfirmed[day];\n  const prob = rawProbable[day];\n  const susp = Math.max(0, rawDailyTotals[day] - conf - prob);\n\n  data.push(\n    {\n      [ONSET_DATE]: isoDate,\n      [CASE_TYPE]: \"Confirmed\",\n      [DAILY_CASES]: conf,\n      [EVENT_LABEL]: ev,\n    },\n    {\n      [ONSET_DATE]: isoDate,\n      [CASE_TYPE]: \"Probable\",\n      [DAILY_CASES]: prob,\n      [EVENT_LABEL]: ev,\n    },\n    {\n      [ONSET_DATE]: isoDate,\n      [CASE_TYPE]: \"Suspect\",\n      [DAILY_CASES]: susp,\n      [EVENT_LABEL]: ev,\n    },\n  );\n}\n\n// Plot: reads only data and the constants above\nconst onsetDates = Array.from(new Set(data.map((r) => r[ONSET_DATE]))).sort();\nconst caseTypes: string[] = [];\nconst eventsByDate = new Map<string, string>();\n\nfor (const row of data) {\n  const dt = row[ONSET_DATE];\n  const ct = row[CASE_TYPE];\n  if (!caseTypes.includes(ct)) caseTypes.push(ct);\n  if (row[EVENT_LABEL] && !eventsByDate.has(dt)) {\n    eventsByDate.set(dt, row[EVENT_LABEL]);\n  }\n}\n\nconst countLookup = new Map<string, number>();\nfor (const row of data) {\n  const key = `${row[ONSET_DATE]}__${row[CASE_TYPE]}`;\n  countLookup.set(key, (countLookup.get(key) ?? 0) + row[DAILY_CASES]);\n}\n\nconst dailyTotals = onsetDates.map((dt) =>\n  caseTypes.reduce(\n    (sum, ct) => sum + (countLookup.get(`${dt}__${ct}`) ?? 0),\n    0,\n  ),\n);\n\nconst cumulativeCases: number[] = [];\nfor (const tot of dailyTotals) {\n  cumulativeCases.push(\n    (cumulativeCases.length ? cumulativeCases[cumulativeCases.length - 1] : 0) +\n      tot,\n  );\n}\n\nconst maxDaily = Math.max(...dailyTotals) * (1 + Y_HEADROOM_RATIO);\nconst maxCumulative =\n  cumulativeCases[cumulativeCases.length - 1] * (1 + Y_HEADROOM_RATIO * 0.5);\n\nconst barSeries = caseTypes.map((ct, idx) => ({\n  type: \"bar\" as const,\n  id: `bar-${ct}`,\n  xAxisId: \"onset\",\n  yAxisId: \"daily\",\n  stack: \"cases\",\n  data: onsetDates.map((dt) => countLookup.get(`${dt}__${ct}`) ?? 0),\n  label: ct,\n  color: t.palette[idx],\n}));\n\nconst series = [\n  ...barSeries,\n  {\n    type: \"line\" as const,\n    id: \"cumulative-line\",\n    xAxisId: \"onset\",\n    yAxisId: \"cumulative\",\n    data: cumulativeCases,\n    label: \"Cumulative cases\",\n    color: t.ink,\n    curve: \"monotoneX\" as const,\n    showMark: false,\n  },\n];\n\nconst totalOutbreakCases = cumulativeCases[cumulativeCases.length - 1];\nconst peakDaily = Math.max(...dailyTotals);\nconst peakDate = onsetDates[dailyTotals.indexOf(peakDaily)];\n\nconst fmtDate = (iso: string) => {\n  const parts = iso.split(\"-\").map(Number);\n  return `${MONTH_ABBR[parts[1] - 1]} ${parts[2]}`;\n};\n\nconst SUBTITLE = `${onsetDates.length} days (${fmtDate(onsetDates[0])}–${fmtDate(onsetDates[onsetDates.length - 1])}) · Total ${totalOutbreakCases.toLocaleString(\"en-US\")} cases, peak ${peakDaily}/day on ${fmtDate(peakDate)}`;\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n  const HEADER_H = 112;\n\n  return (\n    <Box\n      sx={{\n        width,\n        height,\n        bgcolor: t.pageBg,\n        display: \"flex\",\n        flexDirection: \"column\",\n        overflow: \"hidden\",\n      }}\n    >\n      <Box sx={{ pt: \"14px\", px: \"40px\", textAlign: \"center\" }}>\n        <Typography\n          sx={{\n            fontSize: 22,\n            fontWeight: 600,\n            color: t.ink,\n            lineHeight: 1.2,\n            fontFamily: FONT,\n          }}\n        >\n          {TITLE}\n        </Typography>\n        <Typography\n          sx={{\n            fontSize: 15,\n            fontWeight: 400,\n            color: t.inkSoft,\n            mt: \"4px\",\n            lineHeight: 1.2,\n            fontFamily: FONT,\n          }}\n        >\n          {SUBTITLE}\n        </Typography>\n        <Box\n          sx={{\n            display: \"flex\",\n            justifyContent: \"center\",\n            alignItems: \"center\",\n            gap: \"28px\",\n            mt: \"10px\",\n          }}\n        >\n          {caseTypes.map((ct, idx) => (\n            <Box\n              key={ct}\n              sx={{ display: \"flex\", alignItems: \"center\", gap: \"8px\" }}\n            >\n              <Box\n                sx={{\n                  width: 16,\n                  height: 14,\n                  borderRadius: \"2px\",\n                  bgcolor: t.palette[idx],\n                }}\n              />\n              <Typography\n                sx={{\n                  fontSize: 14,\n                  fontWeight: 600,\n                  color: t.ink,\n                  fontFamily: FONT,\n                }}\n              >\n                {ct}\n              </Typography>\n            </Box>\n          ))}\n          <Box sx={{ display: \"flex\", alignItems: \"center\", gap: \"8px\" }}>\n            <Box sx={{ width: 22, height: 3, bgcolor: t.ink }} />\n            <Typography\n              sx={{\n                fontSize: 14,\n                fontWeight: 600,\n                color: t.ink,\n                fontFamily: FONT,\n              }}\n            >\n              Cumulative cases (right axis)\n            </Typography>\n          </Box>\n        </Box>\n      </Box>\n\n      <ChartsContainer\n        width={width}\n        height={height - HEADER_H}\n        series={series}\n        xAxis={[\n          {\n            id: \"onset\",\n            scaleType: \"band\",\n            data: onsetDates,\n            categoryGapRatio: 0.04,\n            height: 60,\n            label: ONSET_DATE,\n            valueFormatter: fmtDate,\n            tickLabelInterval: (_value: string, index: number) =>\n              index % 7 === 0,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft, fontFamily: FONT },\n            labelStyle: { fontSize: 15, fill: t.ink, fontFamily: FONT },\n          },\n        ]}\n        yAxis={[\n          {\n            id: \"daily\",\n            position: \"left\",\n            min: 0,\n            max: maxDaily,\n            width: 80,\n            label: DAILY_CASES,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft, fontFamily: FONT },\n            labelStyle: { fontSize: 15, fill: t.ink, fontFamily: FONT },\n          },\n          {\n            id: \"cumulative\",\n            position: \"right\",\n            min: 0,\n            max: maxCumulative,\n            width: 92,\n            label: \"Cumulative Cases\",\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft, fontFamily: FONT },\n            labelStyle: { fontSize: 15, fill: t.ink, fontFamily: FONT },\n          },\n        ]}\n        margin={{ top: 20, right: 24, bottom: 20, left: 24 }}\n        skipAnimation\n      >\n        <ChartsGrid\n          horizontal\n          sx={{ \"& .MuiChartsGrid-line\": { stroke: t.grid, strokeWidth: 1 } }}\n        />\n        <BarPlot skipAnimation />\n        <LinePlot\n          skipAnimation\n          slotProps={{ line: { sx: { strokeWidth: 3 } } }}\n        />\n        <ChartsXAxis\n          axisId=\"onset\"\n          sx={{ \"& .MuiChartsAxis-line\": { stroke: t.inkSoft } }}\n        />\n        <ChartsYAxis\n          axisId=\"daily\"\n          sx={{ \"& .MuiChartsAxis-line\": { stroke: t.inkSoft } }}\n        />\n        <ChartsYAxis\n          axisId=\"cumulative\"\n          sx={{ \"& .MuiChartsAxis-line\": { stroke: t.inkSoft } }}\n        />\n        {Array.from(eventsByDate.entries()).map(([evDate, evLabel]) => (\n          <ChartsReferenceLine\n            key={evDate}\n            x={evDate}\n            axisId=\"onset\"\n            label={evLabel}\n            labelAlign=\"start\"\n            labelStyle={{\n              fontSize: 14,\n              fontWeight: 600,\n              fill: t.ink,\n              fontFamily: FONT,\n            }}\n            lineStyle={{\n              stroke: t.amber,\n              strokeDasharray: \"6 4\",\n              strokeWidth: 2.5,\n            }}\n          />\n        ))}\n      </ChartsContainer>\n    </Box>\n  );\n}\n"}