{"spec_id":"scatter-ashby-material","library":"muix","language":"javascript","code":"// anyplot.ai\n// scatter-ashby-material: Ashby Material Selection Chart\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 90/100 | Updated: 2026-11-08\n\nimport { ChartsDataProvider } from \"@mui/x-charts/ChartsDataProvider\";\nimport { ChartsSurface } from \"@mui/x-charts/ChartsSurface\";\nimport { ScatterPlot } from \"@mui/x-charts/ScatterChart\";\nimport { ChartsXAxis } from \"@mui/x-charts/ChartsXAxis\";\nimport { ChartsYAxis } from \"@mui/x-charts/ChartsYAxis\";\nimport { ChartsGrid } from \"@mui/x-charts/ChartsGrid\";\nimport { ChartsTooltip } from \"@mui/x-charts/ChartsTooltip\";\nimport { useDrawingArea, useXScale, useYScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst LOG_PAD_SHARE = 0.08; // axis padding on each side as a share of the log span\nconst HULL_MARGIN = 15; // px the family envelopes reach beyond their outermost points\nconst GUIDE_STEP_DECADES = 2; // decades between neighbouring constant-ratio guide lines\nconst MARKER_RADIUS = 6; // px\nconst LABEL_CHAR_WIDTH = 9.2; // px per character of a 16 px family label\nconst LABEL_SWATCH_SPACE = 16; // px the colour swatch takes in front of the label text\nconst LABEL_HEIGHT = 22; // px\nconst LABEL_GAP = 12; // px between an envelope and its label\nconst LABEL_STEP = 16; // px each further try moves the label outward\nconst LABEL_STEPS = 8; // tries per side before a label falls back to its first spot\nconst GUIDE_LABEL_CHAR_WIDTH = 7.8; // px per character of a 14 px guide label\nconst GUIDE_LABEL_HEIGHT = 12; // px the guide label's glyphs rise above its baseline\nconst GUIDE_LABEL_OFFSET = 8; // px between a guide line and its label's baseline\n\n// Columns: set these to your data's column names\nconst MATERIAL = \"Material\"; // role: material\nconst FAMILY = \"Material family\"; // role: family\nconst DENSITY = \"Density (kg/m³)\"; // role: property_x\nconst MODULUS = \"Young's modulus (GPa)\"; // role: property_y\n\n// Data: replace this block with your own records, one object per row\n// Classic density vs. Young's modulus chart: typical handbook values per material\n// as [material, density in kg/m³, Young's modulus in GPa]\nconst data = Object.entries({\n  Metals: [\n    [\"Mild Steel\", 7850, 210], [\"Stainless Steel\", 7900, 193], [\"Cast Iron\", 7200, 110], [\"Aluminum Alloys\", 2700, 70],\n    [\"Titanium Alloys\", 4430, 114], [\"Copper Alloys\", 8900, 120], [\"Magnesium Alloys\", 1740, 45], [\"Nickel Superalloys\", 8200, 210],\n    [\"Zinc Alloys\", 7100, 100], [\"Lead Alloys\", 11340, 16], [\"Tungsten\", 19300, 411], [\"Molybdenum\", 10200, 329],\n    [\"Brass\", 8500, 100], [\"Bronze\", 8800, 110], [\"Chromium\", 7190, 279], [\"Tool Steel\", 7800, 210],\n  ],\n  Polymers: [\n    [\"HDPE\", 950, 0.9], [\"Polypropylene\", 905, 1.5], [\"PVC\", 1400, 3.0], [\"Nylon 6,6\", 1140, 2.8], [\"Polycarbonate\", 1200, 2.4],\n    [\"Acrylic (PMMA)\", 1180, 3.0], [\"ABS\", 1050, 2.2], [\"Polystyrene\", 1050, 3.2], [\"PTFE\", 2170, 0.5], [\"Epoxy Resin\", 1200, 3.0],\n    [\"Polyester Resin\", 1300, 3.5], [\"Phenolic Resin\", 1350, 4.5], [\"Melamine\", 1500, 7.0], [\"Rigid Polyurethane\", 1150, 2.0], [\"PEEK\", 1310, 3.6],\n  ],\n  Ceramics: [\n    [\"Alumina\", 3950, 370], [\"Silicon Carbide\", 3200, 410], [\"Silicon Nitride\", 3200, 310], [\"Zirconia\", 6000, 200], [\"Boron Carbide\", 2520, 450],\n    [\"Tungsten Carbide\", 15600, 600], [\"Magnesia\", 3580, 300], [\"Soda-Lime Glass\", 2500, 72], [\"Borosilicate Glass\", 2230, 63], [\"Concrete\", 2400, 30],\n    [\"Fired Brick\", 1900, 15], [\"Natural Stone\", 2600, 50], [\"Fireclay\", 2100, 25], [\"Cement Paste\", 1900, 20],\n  ],\n  Composites: [\n    [\"CFRP\", 1550, 110], [\"GFRP\", 1900, 25], [\"Kevlar Composite\", 1380, 76], [\"Boron Composite\", 2000, 200], [\"Carbon-Epoxy\", 1600, 140],\n    [\"Glass-Epoxy\", 2000, 40], [\"Al-SiC MMC\", 2900, 120], [\"Cermet\", 6200, 380], [\"Plywood\", 600, 9], [\"Wood (Along Grain)\", 600, 12],\n    [\"Wood (Across Grain)\", 600, 0.8], [\"Bamboo\", 700, 17], [\"Laminated Veneer\", 550, 13],\n  ],\n  Elastomers: [\n    [\"Natural Rubber\", 920, 0.002], [\"Silicone Rubber\", 1200, 0.005], [\"Neoprene\", 1240, 0.01], [\"Butyl Rubber\", 920, 0.0015],\n    [\"Nitrile Rubber\", 1000, 0.004], [\"EPDM\", 860, 0.005], [\"Polyurethane Elastomer\", 1200, 0.03], [\"Latex Rubber\", 940, 0.0015],\n    [\"Isoprene Rubber\", 910, 0.002], [\"SBR\", 940, 0.004], [\"Fluoroelastomer\", 1850, 0.006], [\"Polychloroprene\", 1250, 0.008],\n  ],\n  Foams: [\n    [\"Rigid Polyurethane Foam\", 50, 0.01], [\"Polystyrene Foam\", 25, 0.004], [\"Polyethylene Foam\", 35, 0.002], [\"Cork\", 160, 0.02],\n    [\"Balsa Wood\", 150, 3.0], [\"Aluminum Foam\", 270, 0.8], [\"Flexible PU Foam\", 30, 0.0005], [\"Syntactic Foam\", 550, 2.5],\n    [\"Melamine Foam\", 10, 0.0002], [\"Foamed Glass\", 130, 1.0], [\"Cellular Ceramic Foam\", 400, 1.5], [\"Phenolic Foam\", 60, 0.005],\n  ],\n} as Record<string, [string, number, number][]>).flatMap(([family, rows]) =>\n  rows.map(([material, rho, e]) => ({ [MATERIAL]: material, [FAMILY]: family, [DENSITY]: rho, [MODULUS]: e })),\n);\n\n// Plot: reads only data and the constants above\nconst familyNames = [...new Set(data.map((d) => d[FAMILY]))];\n\n// Convex hull per family (monotone chain) in log-log space, where the axes are linear\nconst families = familyNames.map((name, i) => {\n  const rows = data.filter((d) => d[FAMILY] === name);\n  const sorted = rows\n    .map((d) => [Math.log10(d[DENSITY]), Math.log10(d[MODULUS])])\n    .sort((a, b) => a[0] - b[0] || a[1] - b[1]);\n  const hull: number[][] = [];\n  [sorted, [...sorted].reverse()].forEach((pass) => {\n    const chain: number[][] = [];\n    pass.forEach((p) => {\n      while (chain.length >= 2) {\n        const o = chain[chain.length - 2];\n        const a = chain[chain.length - 1];\n        if ((a[0] - o[0]) * (p[1] - o[1]) - (a[1] - o[1]) * (p[0] - o[0]) > 0) break;\n        chain.pop();\n      }\n      chain.push(p);\n    });\n    chain.pop();\n    hull.push(...chain);\n  });\n  // Fewer than three distinct points have no area; their points stand in for the envelope\n  return { name, color: t.palette[i], rows, outline: hull.length >= 3 ? hull : sorted };\n});\n\n// The envelopes in px, each hull pushed HULL_MARGIN beyond its points, as FamilyRegions draws them\nfunction useEnvelopes() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n  return families.map((family) => {\n    const px = family.outline.map(([lx, ly]) => [xScale(10 ** lx), yScale(10 ** ly)]);\n    const cx = px.reduce((s, p) => s + p[0], 0) / px.length;\n    const cy = px.reduce((s, p) => s + p[1], 0) / px.length;\n    return px.map(([x, y]) => {\n      const len = Math.hypot(x - cx, y - cy) || 1;\n      return [x + ((x - cx) / len) * HULL_MARGIN, y + ((y - cy) / len) * HULL_MARGIN];\n    });\n  });\n}\n\n// Ray casting\nconst insidePolygon = (poly: number[][], x: number, y: number) =>\n  poly.reduce((inside, [ax, ay], i) => {\n    const [bx, by] = poly[(i + 1) % poly.length];\n    return ay > y !== by > y && x < ((bx - ax) * (y - ay)) / (by - ay) + ax ? !inside : inside;\n  }, false);\n\nconst distanceToPolygon = (poly: number[][], x: number, y: number) =>\n  Math.min(\n    ...poly.map(([ax, ay], i) => {\n      const [bx, by] = poly[(i + 1) % poly.length];\n      const len2 = (bx - ax) ** 2 + (by - ay) ** 2 || 1;\n      const s = Math.max(0, Math.min(1, ((x - ax) * (bx - ax) + (y - ay) * (by - ay)) / len2));\n      return Math.hypot(x - ax - s * (bx - ax), y - ay - s * (by - ay));\n    }),\n  );\n\nconst logX = data.map((d) => Math.log10(d[DENSITY]));\nconst logY = data.map((d) => Math.log10(d[MODULUS]));\nconst padX = (Math.max(...logX) - Math.min(...logX)) * LOG_PAD_SHARE;\nconst padY = (Math.max(...logY) - Math.min(...logY)) * LOG_PAD_SHARE;\nconst xMin = 10 ** (Math.min(...logX) - padX);\nconst xMax = 10 ** (Math.max(...logX) + padX);\nconst yMin = 10 ** (Math.min(...logY) - padY);\nconst yMax = 10 ** (Math.max(...logY) + padY);\nconst xDecades = Array.from(\n  { length: Math.floor(Math.log10(xMax)) - Math.ceil(Math.log10(xMin)) + 1 },\n  (_, i) => 10 ** (Math.ceil(Math.log10(xMin)) + i),\n);\nconst yDecades = Array.from(\n  { length: Math.floor(Math.log10(yMax)) - Math.ceil(Math.log10(yMin)) + 1 },\n  (_, i) => 10 ** (Math.ceil(Math.log10(yMin)) + i),\n);\n\n// Constant-ratio guides (y / x = 10^k) every few decades across the data's ratio range,\n// clipped to the axis box; straight and parallel on log-log axes\nconst ratios = data.map((d) => d[MODULUS] / d[DENSITY]);\nconst kLow = Math.ceil(Math.log10(Math.min(...ratios)));\nconst kHigh = Math.floor(Math.log10(Math.max(...ratios)));\nconst guides = Array.from({ length: Math.floor((kHigh - kLow) / GUIDE_STEP_DECADES) + 1 }, (_, i) => {\n  const k = kLow + i * GUIDE_STEP_DECADES;\n  const x0 = Math.max(xMin, yMin / 10 ** k);\n  const x1 = Math.min(xMax, yMax / 10 ** k);\n  return { k, x0, x1, y0: 10 ** k * x0, y1: 10 ** k * x1 };\n}).filter((g) => g.x0 < g.x1);\nconst unitX = DENSITY.match(/\\(([^)]+)\\)/)?.[1] ?? \"\";\nconst unitY = MODULUS.match(/\\(([^)]+)\\)/)?.[1] ?? \"\";\n\nconst TITLE = \"scatter-ashby-material · javascript · muix · anyplot.ai\";\nconst SUBTITLE = `${data.length} materials in ${familyNames.length} families · dashed lines hold the ratio ${MODULUS} / ${DENSITY} constant`;\nconst HEADER_HEIGHT = 84;\n\nfunction FamilyRegions() {\n  const envelopes = useEnvelopes();\n  return (\n    <g>\n      {families.map((family, f) => (\n        <path\n          key={`region-${family.name}`}\n          d={`M ${envelopes[f].map((p) => p.join(\",\")).join(\" L \")} Z`}\n          fill={family.color}\n          fillOpacity={0.1}\n          stroke={family.color}\n          strokeOpacity={0.75}\n          strokeWidth={1.5}\n          strokeLinejoin=\"round\"\n        />\n      ))}\n    </g>\n  );\n}\n\nfunction GuideLines() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n  const area = useDrawingArea();\n  const envelopes = useEnvelopes();\n  return (\n    <g>\n      {guides.map((g) => {\n        const ax = xScale(g.x0);\n        const ay = yScale(g.y0);\n        const bx = xScale(g.x1);\n        const by = yScale(g.y1);\n        const rad = Math.atan2(by - ay, bx - ax);\n        const [ux, uy] = [Math.cos(rad), Math.sin(rad)];\n        const [nx, ny] = [uy, -ux]; // normal pointing above the line\n        const w = (`10${g.k} ${unitY}/(${unitX})`.length * GUIDE_LABEL_CHAR_WIDTH) / 2;\n        // The label slides along its line to the spot that keeps it furthest from every envelope\n        // (negative inside one) and inside the plot\n        const spots = Array.from({ length: 33 }, (_, i) => 0.1 + i * 0.025).map((share) => {\n          const cx = ax + (bx - ax) * share + nx * GUIDE_LABEL_OFFSET;\n          const cy = ay + (by - ay) * share + ny * GUIDE_LABEL_OFFSET;\n          const samples = [-1, -0.5, 0, 0.5, 1].flatMap((s) =>\n            [0, GUIDE_LABEL_HEIGHT].map((h) => [cx + ux * s * w + nx * h, cy + uy * s * w + ny * h]),\n          );\n          const clearance = Math.min(\n            ...samples.map(([sx, sy]) => {\n              if (sx < area.left || sx > area.left + area.width || sy < area.top || sy > area.top + area.height) return -Infinity;\n              return Math.min(...envelopes.map((poly) => (insidePolygon(poly, sx, sy) ? -1 : 1) * distanceToPolygon(poly, sx, sy)));\n            }),\n          );\n          return { cx, cy, clearance };\n        });\n        const spot = spots.reduce((best, s) => (s.clearance > best.clearance ? s : best));\n        return (\n          <g key={`guide-${g.k}`}>\n            <line x1={ax} y1={ay} x2={bx} y2={by} stroke={t.inkSoft} strokeWidth={1.25} strokeDasharray=\"7 6\" strokeOpacity={0.6} />\n            <text\n              transform={`translate(${spot.cx}, ${spot.cy}) rotate(${(rad * 180) / Math.PI})`}\n              textAnchor=\"middle\"\n              fontSize={14}\n              fill={t.inkSoft}\n              stroke={t.pageBg}\n              strokeWidth={4}\n              paintOrder=\"stroke\"\n            >\n              10<tspan dy={-6}>{g.k}</tspan>\n              <tspan dy={6}>{` ${unitY}/(${unitX})`}</tspan>\n            </text>\n          </g>\n        );\n      })}\n    </g>\n  );\n}\n\nfunction FamilyLabels() {\n  const xScale = useXScale();\n  const yScale = useYScale();\n  const area = useDrawingArea();\n  const hulls = useEnvelopes();\n  const markers = data.map((d) => [xScale(d[DENSITY]), yScale(d[MODULUS])]);\n  // Each label tries above, below, right of and left of its envelope, stepping further out, and takes\n  // the first spot inside the plot that touches no marker, no other label and no other envelope, and\n  // that lies nearer its own envelope than any other\n  const placed: { x: number; y: number; w: number }[] = [];\n  families.forEach((family, f) => {\n    const w = family.name.length * LABEL_CHAR_WIDTH + LABEL_SWATCH_SPACE;\n    const xs = hulls[f].map((p) => p[0]);\n    const ys = hulls[f].map((p) => p[1]);\n    const midX = (Math.min(...xs) + Math.max(...xs)) / 2;\n    const midY = (Math.min(...ys) + Math.max(...ys)) / 2;\n    const candidates = Array.from({ length: LABEL_STEPS }, (_, s) => LABEL_GAP + s * LABEL_STEP).flatMap((gap) => [\n      { x: midX, y: Math.min(...ys) - gap - LABEL_HEIGHT / 2 },\n      { x: midX, y: Math.max(...ys) + gap + LABEL_HEIGHT / 2 },\n      { x: Math.max(...xs) + gap + w / 2, y: midY },\n      { x: Math.min(...xs) - gap - w / 2, y: midY },\n    ]);\n    const free = candidates.find(({ x, y }) => {\n      const x0 = x - w / 2;\n      const x1 = x + w / 2;\n      const y0 = y - LABEL_HEIGHT / 2;\n      const y1 = y + LABEL_HEIGHT / 2;\n      if (x0 < area.left || x1 > area.left + area.width || y0 < area.top || y1 > area.top + area.height) return false;\n      if (markers.some(([mx, my]) => mx > x0 - MARKER_RADIUS && mx < x1 + MARKER_RADIUS && my > y0 - MARKER_RADIUS && my < y1 + MARKER_RADIUS)) return false;\n      if (placed.some((p) => x0 < p.x + p.w / 2 && p.x - p.w / 2 < x1 && Math.abs(p.y - y) < LABEL_HEIGHT)) return false;\n      const samples = [x0, x, x1].flatMap((sx) => [y0, y, y1].map((sy) => [sx, sy]));\n      // A sample inside another family's envelope rules the spot out\n      if (hulls.some((hull, g) => g !== f && samples.some(([sx, sy]) => insidePolygon(hull, sx, sy)))) return false;\n      const distances = hulls.map((hull) => distanceToPolygon(hull, x, y));\n      return distances.every((d, g) => g === f || d > distances[f]);\n    });\n    placed.push({ ...(free ?? candidates[0]), w });\n  });\n  return (\n    <g>\n      {families.map((family, f) => {\n        const { x, y, w } = placed[f];\n        // A swatch in the region's colour ties the label to its envelope; the text stays in ink\n        const left = x - w / 2;\n        return (\n          <g key={`label-${family.name}`}>\n            <circle cx={left + 5} cy={y} r={6} fill={family.color} stroke={t.pageBg} strokeWidth={2} />\n            <text\n              x={left + LABEL_SWATCH_SPACE}\n              y={y}\n              dominantBaseline=\"central\"\n              fontSize={16}\n              fontWeight={600}\n              fill={t.ink}\n              stroke={t.pageBg}\n              strokeWidth={4}\n              paintOrder=\"stroke\"\n            >\n              {family.name}\n            </text>\n          </g>\n        );\n      })}\n    </g>\n  );\n}\n\nexport default function Chart() {\n  const { width, height } = window.ANYPLOT_SIZE;\n  return (\n    <div style={{ width, height, background: t.pageBg, display: \"flex\", flexDirection: \"column\" }}>\n      <div\n        style={{\n          height: HEADER_HEIGHT,\n          display: \"flex\",\n          flexDirection: \"column\",\n          alignItems: \"center\",\n          justifyContent: \"center\",\n          gap: 6,\n        }}\n      >\n        <div style={{ fontSize: 22, fontWeight: 600, color: t.ink }}>{TITLE}</div>\n        <div style={{ fontSize: 15, color: t.inkSoft }}>{SUBTITLE}</div>\n      </div>\n      <ChartsDataProvider\n        width={width}\n        height={height - HEADER_HEIGHT}\n        margin={{ top: 12, right: 48, bottom: 16, left: 24 }}\n        skipAnimation\n        series={families.map((family) => ({\n          type: \"scatter\" as const,\n          id: family.name,\n          label: family.name,\n          color: family.color,\n          markerSize: MARKER_RADIUS,\n          data: family.rows.map((d, j) => ({ id: `${family.name}-${j}`, x: d[DENSITY], y: d[MODULUS], material: d[MATERIAL] })),\n          valueFormatter: (p: any) => `${p.material}: ${p.x} ${unitX}, ${p.y} ${unitY}`,\n        }))}\n        xAxis={[\n          {\n            id: \"density\",\n            scaleType: \"log\",\n            min: xMin,\n            max: xMax,\n            tickInterval: xDecades,\n            label: DENSITY,\n            height: 72,\n            valueFormatter: (v: number) => (v >= 1 ? v.toLocaleString(\"en-US\") : `${Number(v.toPrecision(1))}`),\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            id: \"modulus\",\n            scaleType: \"log\",\n            min: yMin,\n            max: yMax,\n            tickInterval: yDecades,\n            label: MODULUS,\n            width: 84,\n            valueFormatter: (v: number) => (v >= 1 ? v.toLocaleString(\"en-US\") : `${Number(v.toPrecision(1))}`),\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n      >\n        <ChartsSurface\n          sx={{\n            \"& .MuiChartsGrid-line\": { stroke: t.grid, strokeWidth: 1 },\n            \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n            \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n          }}\n        >\n          <ChartsGrid vertical horizontal />\n          <FamilyRegions />\n          <GuideLines />\n          <ScatterPlot />\n          <FamilyLabels />\n          <ChartsXAxis axisId=\"density\" />\n          <ChartsYAxis axisId=\"modulus\" />\n        </ChartsSurface>\n        <ChartsTooltip trigger=\"item\" />\n      </ChartsDataProvider>\n    </div>\n  );\n}\n"}