Skip to the content

Charts

scatter-chart

Points placed by two numbers, optionally sized by a third (a bubble chart) and grouped by a category, with the nearest point read under the pointer and every point reachable by arrow keys.

Charts

When to use it

Showing how two measures relate across many things: does one rise with the other, which stand apart. Give size for a third measure as bubble area. For change over time use line-chart; for one measure across categories use bar-chart or dot-plot; for thousands of overlapping points use density-chart.

See it working

The demonstration the browser checks drive, with the keyboard as well as the pointer. More of it is on the Charts page.

Scatter and bubble

  • Tea
  • Coffee
  • Cocoa
Price against rating, bubbles sized by units sold
namePriceRatingSoldkind
Blend 16.23.1626Tea
Blend 326.44.9540Coffee
Blend 157.64.5261Cocoa
Blend 238.14.1429Coffee
Blend 98.83.6369Cocoa
Blend 35115430Coffee
Blend 711.35189Tea
Blend 3111.63.546Tea
Blend 1812.43.3120Cocoa
Blend 1412.43.952Coffee
Blend 612.63.6361Cocoa
Blend 1613.73.9608Tea
Blend 314.43.5372Cocoa
Blend 2715.33.7475Cocoa
Blend 2815.94.5626Tea
Blend 2615.94.643Coffee
Blend 11164.2448Coffee
Blend 29164.6298Coffee
Blend 3416.74.4637Tea
Blend 2516.74.9621Tea
Blend 3317.43411Cocoa
Blend 2017.43.766Coffee
Blend 3017.64.5371Cocoa
Blend 2118.34.8369Cocoa
Blend 218.64283Coffee
Blend 1718.74.4238Coffee
Blend 419.13.5134Tea
Blend 1019.73.1588Tea
Blend 519.84158Coffee
Blend 3620.54.2538Cocoa
Blend 1320.93.1145Tea
Blend 2220.94.3592Tea
Blend 821.83.4126Coffee
Blend 24224.9543Cocoa
Blend 1922.43.6154Tea
Blend 1223.44.2593Cocoa

Histogram

Delivery times
MinutesCount
14 – 161
16 – 182
18 – 203
20 – 223
22 – 245
24 – 2620
26 – 2825
28 – 3023
30 – 3225
32 – 3428
34 – 3634
36 – 3822
38 – 4017
40 – 4218
42 – 447
44 – 466
46 – 480
48 – 501

Box plot and violin

Response time by region
region (Milliseconds)CountLowestFirst quartileMedianThird quartileHighestOutliers
North4189112119128144260
South40109132144.5152.25174
East41136157172185200330
West40140171.5191.5212.25234
Response time by region, as violins
region (ms)CountLowestFirst quartileMedianThird quartileHighestOutliers
North4189112119128144260
South40109132144.5152.25174
East41136157172185200330
West40140171.5191.5212.25234

Fan chart

  • Observed
  • Forecast (median)
  • 90% interval
  • 50% interval
Visitors per week, observed and forecast
WeekObservedForecast (median)90% interval50% interval
1108
2111
3110
4107
5109
6116
7125
8130
9129
10127
11127
12133
13142
14148142142 – 142142 – 142
15144.6139.1 – 150.6142 – 147.4
16147.2136.2 – 159.2142 – 152.8
17149.8133.3 – 167.8142 – 158.2
18152.4130.4 – 176.4142 – 163.6
19155127.5 – 185142 – 169
20157.6124.6 – 193.6142 – 174.4
21160.2121.7 – 202.2142 – 179.8
22162.8118.8 – 210.8142 – 185.2
23165.4115.9 – 219.4142 – 190.6
24168113 – 228142 – 196

Small multiples

  • North
  • South
  • East
  • West
  • Centre
  • Coast
Monthly visits by region, on one shared scale
regionMonthVisits
North146
North251
North352
North450
North545
North638
North731
North825
North921
North1021
North1124
North1229
South159
South263
South363
South460
South555
South650
South746
South844
South946
South1051
South1159
South1267
East165
East264
East359
East452
East544
East638
East734
East834
East937
East1042
East1148
East1254
West172
West269
West364
West459
West555
West653
West755
West860
West968
West1076
West1184
West1289
Centre172
Centre265
Centre357
Centre451
Centre547
Centre647
Centre750
Centre855
Centre962
Centre1067
Centre1171
Centre1271
Coast173
Coast268
Coast364
Coast462
Coast564
Coast669
Coast777
Coast885
Coast993
Coast1098
Coast11100
Coast1299

Bars to 100 percent

  • Web
  • App
  • Shop
Orders by channel per quarter, as shares
quarterWebAppShop
Q1320 (49.2%)210 (32.3%)120 (18.5%)
Q2360 (48.6%)270 (36.5%)110 (14.9%)
Q3400 (48.2%)330 (39.8%)100 (12%)
Q4440 (47.8%)390 (42.4%)90 (9.8%)

Treemap

2,750
Spending by area
PartValueShare
Housing / Rent1,20043.6%
Housing / Power1405.1%
Housing / Water602.2%
Housing / Repairs903.3%
Food / Groceries42015.3%
Food / Cafés903.3%
Food / Takeaway702.5%
Travel / Transit pass1104%
Travel / Bike301.1%
Travel / Trains1204.4%
Leisure / Books401.5%
Leisure / Music250.9%
Leisure / Sport552%
Savings30010.9%

Top

Sunburst

Spending by area, as rings
PartValueShare
Housing / Rent1,20043.6%
Housing / Power1405.1%
Housing / Water602.2%
Housing / Repairs903.3%
Food / Groceries42015.3%
Food / Cafés903.3%
Food / Takeaway702.5%
Travel / Transit pass1104%
Travel / Bike301.1%
Travel / Trains1204.4%
Leisure / Books401.5%
Leisure / Music250.9%
Leisure / Sport552%
Savings30010.9%
  • Housing54.2%
  • Food21.1%
  • Travel9.5%
  • Leisure4.4%
  • Savings10.9%

Circle packing

Spending by area, as circles
PartValueShare
Housing / Rent1,20043.6%
Housing / Power1405.1%
Housing / Water602.2%
Housing / Repairs903.3%
Food / Groceries42015.3%
Food / Cafés903.3%
Food / Takeaway702.5%
Travel / Transit pass1104%
Travel / Bike301.1%
Travel / Trains1204.4%
Leisure / Books401.5%
Leisure / Music250.9%
Leisure / Sport552%
Savings30010.9%

Sankey

Where the money goes
FromToAmount
SalaryBudget2,400
FreelanceBudget600
BudgetRent1,200
BudgetFood600
BudgetTravel300
BudgetSaved900

Network graph

  • App
  • Library
  • Tool
Parts of an app and what they use
NodeGroupLinked to
AppAppUi, Charts, Maps, Forms, Three, Tests
UiLibraryApp, Theme, Icons, Motion, Forms
ChartsLibraryApp, Maths, Theme
MapsLibraryApp, Maths, Theme
MathsLibraryCharts, Maps
MotionLibraryUi, Theme
ThreeToolTheme, App
ThemeToolUi, Charts, Maps, Motion, Three
IconsToolUi
DatesToolForms
FormsToolApp, Ui, Dates
TestsToolApp

Calendar heatmap

Workouts per day
dayWorkouts
2026-01-014
2026-01-028
2026-01-032
2026-01-042
2026-01-089
2026-01-095
2026-01-138
2026-01-1511
2026-01-172
2026-01-184
2026-01-196
2026-01-2110
2026-01-237
2026-01-243
2026-01-253
2026-01-268
2026-01-277
2026-01-2910
2026-01-309
2026-02-013
2026-02-0211
2026-02-034
2026-02-047
2026-02-058
2026-02-067
2026-02-082
2026-02-096
2026-02-114
2026-02-126
2026-02-136
2026-02-142
2026-02-152
2026-02-167
2026-02-214
2026-02-224
2026-02-2511
2026-02-264
2026-02-275
2026-03-027
2026-03-036
2026-03-044
2026-03-0510
2026-03-0611
2026-03-083
2026-03-116
2026-03-136
2026-03-166
2026-03-188
2026-03-204
2026-03-212
2026-03-2312
2026-03-2412
2026-03-259
2026-03-2710
2026-03-281
2026-03-293
2026-03-306
2026-04-015
2026-04-029
2026-04-035
2026-04-043
2026-04-065
2026-04-079
2026-04-0910
2026-04-109
2026-04-136
2026-04-1410
2026-04-1611
2026-04-1710
2026-04-194
2026-04-215
2026-04-236
2026-04-252
2026-04-262
2026-04-2812
2026-04-295
2026-04-309
2026-05-031
2026-05-0412
2026-05-058
2026-05-075
2026-05-088
2026-05-104
2026-05-125
2026-05-135
2026-05-158
2026-05-163
2026-05-172
2026-05-1811
2026-05-209
2026-05-218
2026-05-224
2026-05-232
2026-05-287
2026-05-2910
2026-05-312
2026-06-0210
2026-06-054
2026-06-063
2026-06-072
2026-06-088
2026-06-115
2026-06-124
2026-06-133
2026-06-141
2026-06-1511
2026-06-164
2026-06-197
2026-06-224
2026-06-239
2026-06-245
2026-06-257
2026-06-282
2026-06-295
2026-06-3010

Gantt chart

Launch plan
TaskGroupStartEndDoneAfter
ResearchProductMar 2, 2026Mar 10, 2026100%
DesignProductMar 9, 2026Mar 20, 2026100%Research
BuildProductMar 16, 2026Apr 10, 202645%Design
TestProductApr 6, 2026Apr 17, 20260%Build
Write the storyMarketingMar 23, 2026Apr 3, 202660%
Update the siteMarketingApr 6, 2026Apr 14, 20260%Write the story
LaunchMarketingApr 20, 2026MilestoneTest, Update the site

Density

Trip length against fare
#Distance (km)Fare
11.43.9
21.54.1
31.55.5
41.55.9
51.64.2
61.66.2
71.66.9
81.74.3
91.76.1
101.76.3
111.77.2
121.77.7
131.85.9
141.86.1
151.86.4
161.86.5
171.87
181.95.5
191.97.5
2025.5
2127.8
222.14.4
232.14.9
242.16.6
252.17
262.17.5
272.17.8
282.18
292.18.6
302.25.4
312.27
322.27.5
332.27.6
342.27.8
352.27.8
362.27.9
372.28
382.28.1
392.28.2
402.28.7
412.28.9
422.36
432.36.7
442.37
452.37.8
462.38.2
472.38.2
482.38.5
492.39
502.46.7
512.46.8
522.47.7
532.48
542.48.1
552.48.2
562.49.3
572.55.6
582.55.8
592.56.7
602.57
612.57.3
622.57.5
632.58.1
642.58.3
652.58.5
662.58.5
672.510.8
682.510.9
692.67.3
702.67.8
712.67.9
722.68
732.68.2
742.69.6
752.69.7
762.69.9
772.610.6
782.77.8
792.78.4
802.78.5
812.79.1
822.86.4
832.87
842.87.2
852.87.5
862.87.7
872.88
882.88.4
892.88.6
902.89.3
912.89.6
922.89.6
932.89.7
942.89.8
952.89.9
962.810.4
972.98.1
982.98.4
992.98.7
1002.98.7
1012.98.9
1022.99.2
1032.99.3
1042.99.5
1052.99.7
1062.99.7
1072.99.8
1082.99.9
10938.1
11038.4
11138.6
11239.7
11339.9
114310.2
115310.9
1163.17.9
1173.18.4
1183.18.8
1193.18.8
1203.19
1213.19.4
1223.19.4
1233.110.1
1243.110.2
1253.110.3
1263.110.3
1273.110.3
1283.27.7
1293.28.8
1303.28.9
1313.29.3
1323.29.4
1333.29.5
1343.29.5
1353.29.5
1363.29.5
1373.29.6
1383.29.9
1393.29.9
1403.210.1
1413.210.4
1423.211.1
1433.211.4
1443.211.5
1453.39
1463.39.1
1473.39.8
1483.310
1493.310
1503.310.3
1513.310.3
1523.310.4
1533.310.5
1543.310.6
1553.311
1563.311.2
1573.311.5
1583.49.5
1593.410.5
1603.411.1
1613.411.2
1623.411.3
1633.411.6
1643.59.1
1653.59.3
1663.510.1
1673.511.5
1683.68.3
1693.610.7
1703.610.9
1713.611.9
1723.78.8
1733.79.2
1743.79.3
1753.79.6
1763.710.6
1773.711
1783.711.1
1793.711.3
1803.712
1813.712.4
1823.712.7
1833.810.6
1843.811
1853.811.1
1863.811.5
1873.811.5
1883.811.7
1893.812.1
1903.812.1
1913.813.3
1923.813.5
1933.99.1
1943.99.2
1953.99.9
1963.910
1973.911.5
1983.911.6
19949.8
200410.7
201411.6
202412.1
2034.19.7
2044.111.5
2054.111.9
2064.210.1
2074.210.9
2084.211.4
2094.211.6
2104.211.9
2114.213.9
2124.411
2134.412.3
2144.512.1
2154.612.2
2164.613.5
2174.711.4
2184.712.9
2194.912.4
220515.1
221819.6
2228.520
2238.621.4
2248.622.7
2258.922.4
226921.3
2279.320
2289.422
2299.722.4
2309.722.7
2319.822.9
2329.824.1
2339.824.2
2349.923.9
2359.924.4
2369.924.6
2379.925.3
2381023.7
23910.123.2
24010.123.2
24110.222.5
24210.324.3
24310.324.3
24410.324.5
24510.524.4
24610.826
24710.925.5
24810.925.7
2491124.6
2501127
2511127.7
25211.124.5
25311.124.9
25411.125.6
25511.125.9
25611.126
25711.126.8
25811.226.4
25911.226.6
26011.226.8
26111.325.5
26211.325.8
26311.327.4
26411.425.2
26511.427.3
26611.428.1
26711.428.1
26811.525.8
26911.526.3
27011.527.4
27111.628.6
27211.628.9
27311.726.5
27411.726.6
27511.727.5
27611.728
27711.827
27811.827.1
27911.925.6
28011.926.3
28111.927.7
28211.929
2831227.2
2841227.3
2851228.7
2861229.2
2871230.1
28812.129.8
28912.130
29012.227.2
29112.227.4
29212.328.1
29312.329
29412.429.4
29512.527.1
29612.529.1
29712.530.5
29812.628.3
29912.629.2
30012.728.6
30112.829.3
30212.829.5
30312.928.8
30412.928.8
30512.929.8
30612.930.1
30712.931.1
30812.932.3
3091330.2
3101331.2
3111331.9
3121332.4
31313.129.5
31413.131.9
31513.230.7
31613.231
31713.329.6
31813.330.6
31913.332.1
32013.332.6
32113.530.5
32213.531.8
32313.629.9
32413.631.8
32513.730.6
32613.731.1
32713.732.4
32813.832.7
32913.932.4
3301432.8
3311434.7
33214.131.1
33314.133.7
33414.231.7
33514.233.4
33614.432.7
33714.833.6
33814.932.6
33914.935.4
34015.134.5

Radar

  • Basic
  • Plus
  • Pro
Three plans compared
measureBasicPlusPro
Speed345
Storage245
Support235
Price542
Security345
Sharing254

Waterfall

From revenue to profit
StepChangeRunning total
Revenue500 (Total)500
Costs-220 (Fall)280
Marketing-80 (Fall)200
Other income+30 (Rise)230
Tax-46 (Fall)184
Profit184 (Total)184

Funnel

Sign-up steps
StepCountof the first stepof the step before
Visited1,200100%
Started64053.3%53.3%
Confirmed email41034.2%64.1%
Finished29024.2%70.7%

Bullet

Quarter targets
MeasureValueTargetBands
Revenue270250150, 225, 300
New customers1,4001,6001,000, 1,500, 2,000
Satisfaction4.14.33, 4, 5

Candlestick

Price by day
PeriodOpenHighLowClose
Mar 2, 20264040.538.239.4
Mar 3, 202639.440.83939.7
Mar 4, 202639.742.339.441.3
Mar 5, 202641.341.439.240.2
Mar 6, 202640.240.838.139
Mar 7, 20263940.738.640.1
Mar 8, 202640.140.539.139.8
Mar 9, 202639.840.138.639.7
Mar 10, 202639.740.339.439.4
Mar 11, 202639.440.539.140.2
Mar 12, 202640.241.238.839.4
Mar 13, 202639.441.538.340.8
Mar 14, 202640.841.340.441.1
Mar 15, 202641.141.740.841.5
Mar 16, 202641.542.640.540.8
Mar 17, 202640.841.739.940.2
Mar 18, 202640.241.439.240.5
Mar 19, 202640.541.239.541.1
Mar 20, 202641.141.140.140.8
Mar 21, 202640.84240.341.7
Mar 22, 202641.741.940.740.7
Mar 23, 202640.742.540.741.9
Mar 24, 202641.942.740.540.7
Mar 25, 202640.740.839.639.8
Mar 26, 202639.842.33941.4
Mar 27, 202641.441.541.141.1
Mar 28, 202641.14240.440.6
Mar 29, 202640.640.839.540.1
Mar 30, 202640.141.63941.1
Mar 31, 202641.141.940.340.5

Chord diagram

Moves between neighbourhoods
FromToAmount
NorthSouth120
NorthEast40
NorthWest30
NorthCentre60
SouthNorth80
SouthEast60
SouthWest20
SouthCentre40
EastNorth30
EastSouth90
EastWest50
EastCentre70
WestNorth20
WestSouth30
WestEast40
WestCentre35
CentreNorth55
CentreSouth45
CentreEast65
CentreWest30

Parallel coordinates

  • Power
  • Light
  • Value
Laptops compared
namekindPriceWeight (kg)Battery (h)Screen (in)
Model APower1,2211.11216.6
Model BLight1,4661.81315.6
Model CValue9152.4716.9
Model DPower1,5961.91215.5
Model ELight7421.3815.1
Model FValue1,4541.2715.8
Model GPower8841.91116
Model HLight7071.31714.3
Model IValue76621315.4
Model JPower1,2531814
Model KLight1,3491.1813.8
Model LValue1,5001.81114.6
Model MPower1,7832.21414.4
Model NLight1,60421314.5

Dot plot

  • Before
  • After
Satisfaction before and after
teamBeforeAfter
Support6278
Sales7074
Product5571
Finance6663
Design7281
Every response time, by region
#regionMilliseconds
15North89
25North90
27North93
37North99
23North100
29North105
40North105
16North107
12North108
31North108
14North112
17North112
18North112
33North113
38North113
19North114
21North116
5North117
35North117
1North119
7North119
22North120
4North121
24North121
13North125
3North126
6North126
9North126
11North126
34North126
32North128
28North129
2North130
36North130
26North131
30North132
39North132
8North136
20North140
10North144
161North260
63South109
77South113
57South115
78South117
80South123
71South129
42South131
69South131
43South132
46South132
74South132
48South134
68South136
45South138
76South139
50South140
58South140
59South140
67South142
51South144
44South145
72South145
75South145
55South146
66South146
64South147
62South148
49South150
60South150
52South152
65South153
41South154
56South154
54South158
61South158
73South158
79South159
70South172
53South173
47South174
90East136
108East144
118East144
84East147
81East149
114East149
93East150
107East153
110East154
109East156
112East157
85East161
92East163
94East164
89East167
86East168
88East168
96East168
113East169
99East170
104East172
97East173
102East173
103East174
91East175
119East176
95East178
100East178
87East180
101East180
98East185
115East185
120East185
111East187
82East193
83East193
105East193
116East194
106East196
117East200
162East330
140West140
126West141
145West149
146West150
136West156
131West160
144West165
134West167
149West168
137West170
138West172
143West178
124West179
123West183
156West186
157West186
125West187
151West187
133West189
135West190
141West193
147West193
128West195
127West200
129West204
121West206
130West206
148West206
139West209
154West212
132West213
155West213
160West215
153West219
150West221
159West222
122West224
152West225
142West226
158West234

Stream

  • Jazz
  • Folk
  • Rock
  • Electronic
Plays by genre
yearJazzFolkRockElectronic
2,01520305315
2,01626345018
2,01729374521
2,01828384124
2,01927374027
2,02029354130
2,02134314133
2,02240273836
2,02344243439
2,02444222942
2,02543222745
2,02644242848

Slope

Share of trips by mode
mode20162026Change
Car5241-11 (Fell)
Bike918+9 (Rose)
Transit2427+3 (Rose)
Walking1312-1 (Fell)

Brush

Visits per day, the stretch chosen below
dayVisits
May 1, 2026334
May 2, 2026348
May 3, 2026344
May 4, 2026344
May 5, 2026331
May 6, 2026324
May 7, 2026326
May 8, 2026334
May 9, 2026328
May 10, 2026322
May 11, 2026313
May 12, 2026306
May 13, 2026311
May 14, 2026309
May 15, 2026289
May 16, 2026289
May 17, 2026287
May 18, 2026290
May 19, 2026285
May 20, 2026262
May 21, 2026279
May 22, 2026279
May 23, 2026265
May 24, 2026288
May 25, 2026278
May 26, 2026282
May 27, 2026283
May 28, 2026289
May 29, 2026303
May 30, 2026307
May 31, 2026315
Jun 1, 2026313
Jun 2, 2026335
Jun 3, 2026337
Jun 4, 2026345
Jun 5, 2026352
Jun 6, 2026363
Jun 7, 2026381
Jun 8, 2026351
Jun 9, 2026378
Jun 10, 2026354
Jun 11, 2026372
Jun 12, 2026371
Jun 13, 2026363
Jun 14, 2026366
Jun 15, 2026360
Jun 16, 2026350
Jun 17, 2026355
Jun 18, 2026347
Jun 19, 2026342
Jun 20, 2026339
Jun 21, 2026336
Jun 22, 2026303
Jun 23, 2026301
Jun 24, 2026317
Jun 25, 2026317
Jun 26, 2026313
Jun 27, 2026315
Jun 28, 2026308
Jun 29, 2026304

120–179

Add it

npx shadcn@latest add @rivier-ui/scatter-chart

The registry is named once in components.json: see Installation.

Example

Import it from @/components/viz/scatter-chart.

<ScatterChart
  label="Price against rating"
  data={[
    { name: "Alder", price: 12, rating: 4.1, sold: 320, kind: "Tea" },
    { name: "Birch", price: 18, rating: 4.6, sold: 120, kind: "Tea" },
    { name: "Cedar", price: 9, rating: 3.8, sold: 540, kind: "Coffee" },
  ]}
  x="price"
  y="rating"
  size="sold"
  group="kind"
  name="name"
  xLabel="Price"
  yLabel="Rating"
/>

What it needs

A client component: it uses state, effects or browser behaviour. Packages: d3-delaunay, d3-scale.

It imports

It is used by

Source

The whole file. Once copied it is yours: the registry item holds the same text.

src/components/viz/scatter-chart.tsx
"use client";
/**
 * @name scatter-chart
 * @category viz
 * @description Points placed by two numbers, optionally sized by a third (a bubble chart) and grouped by a category, with the nearest point read under the pointer and every point reachable by arrow keys.
 * @when Showing how two measures relate across many things: does one rise with the other, which stand apart. Give `size` for a third measure as bubble area. For change over time use line-chart; for one measure across categories use bar-chart or dot-plot; for thousands of overlapping points use density-chart.
 * @example
 * <ScatterChart
 *   label="Price against rating"
 *   data={[
 *     { name: "Alder", price: 12, rating: 4.1, sold: 320, kind: "Tea" },
 *     { name: "Birch", price: 18, rating: 4.6, sold: 120, kind: "Tea" },
 *     { name: "Cedar", price: 9, rating: 3.8, sold: 540, kind: "Coffee" },
 *   ]}
 *   x="price"
 *   y="rating"
 *   size="sold"
 *   group="kind"
 *   name="name"
 *   xLabel="Price"
 *   yLabel="Rating"
 * />
 */
import { Delaunay } from "d3-delaunay";
import { scaleSqrt } from "d3-scale";
import { useMemo, type PointerEvent } from "react";
import { cn } from "@/lib/cn";
import {
  axisNumberFormatter,
  ChartAxis,
  ChartContainer,
  ChartEmpty,
  ChartGrid,
  ChartLegend,
  ChartMark,
  chartLinear,
  chartSeries,
  ChartSvg,
  ChartTooltip,
  formatNumber,
  readNumber,
  useChartCursor,
  widestText,
  type ChartBaseProps,
} from "@/components/viz/chart";
 
export type ScatterChartProps<T extends object> = ChartBaseProps & {
  /** One object per point. Rows without a number for x or y are left out. */
  data: readonly T[];
  /** The field for the horizontal position. */
  x: keyof T & string;
  /** The field for the vertical position. */
  y: keyof T & string;
  /** A field whose number sets each point's area: a bubble chart. */
  size?: keyof T & string;
  /** A field naming each point's group: one colour and shape per group, in order of first appearance. */
  group?: keyof T & string;
  /** The groups in a fixed order, so a group keeps its colour when another is filtered out. */
  groups?: readonly string[];
  /** A field naming each point, for the tooltip and the table. */
  name?: keyof T & string;
  /** The names of the measures, on the axes, in the tooltip and in the table. Default: the field names. */
  xLabel?: string;
  yLabel?: string;
  sizeLabel?: string;
  /** Start an axis at zero. Default false: a scatter is read by position, not length. */
  zeroX?: boolean;
  zeroY?: boolean;
  showGrid?: boolean;
  /** Default: shown when there are two or more groups. */
  showLegend?: boolean;
  /** The largest bubble's radius in pixels. Default: a twelfth of the shorter side, at most 28. */
  maxRadius?: number;
};
 
type Point = {
  row: number;
  x: number;
  y: number;
  size: number | null;
  group: number;
  name: string;
};
 
export function ScatterChart<T extends object>({
  data,
  x,
  y,
  size,
  group,
  groups,
  name,
  xLabel,
  yLabel,
  sizeLabel,
  zeroX = false,
  zeroY = false,
  showGrid = true,
  showLegend,
  maxRadius,
  label,
  aspect,
  height,
  emptyLabel,
  locale,
  formatValue,
  className,
  ...props
}: ScatterChartProps<T>) {
  const model = useMemo(() => {
    const read = (row: T, key: string | undefined): string => (key ? String((row as Record<string, unknown>)[key] ?? "") : "");
    const order = groups ? [...groups] : [...new Set(data.map((row) => read(row, group)))];
    const points: Point[] = [];
    data.forEach((row, index) => {
      const px = readNumber(row, x);
      const py = readNumber(row, y);
      if (px === null || py === null) return;
      const g = group ? order.indexOf(read(row, group)) : 0;
      points.push({
        row: index,
        x: px,
        y: py,
        size: size ? readNumber(row, size) : null,
        group: g,
        name: read(row, name),
      });
    });
    // Reading order is left to right, so the arrow keys follow the x axis.
    points.sort((a, b) => a.x - b.x || a.y - b.y);
    return { points, order };
  }, [data, x, y, size, group, groups, name]);
 
  const { points, order } = model;
  const cursor = useChartCursor(points.length);
  const value = formatValue ?? ((number: number) => formatNumber(number, locale));
  const names = {
    x: xLabel ?? x,
    y: yLabel ?? y,
    size: sizeLabel ?? size ?? "",
  };
  const grouped = Boolean(group) && order.length > 0;
  const table = {
    caption: label,
    columns: [...(name ? [name] : ["#"]), names.x, names.y, ...(size ? [names.size] : []), ...(grouped ? [group ?? ""] : [])],
    rows: points.map((point, index) => [
      name ? point.name : String(index + 1),
      value(point.x),
      value(point.y),
      ...(size ? [point.size === null ? "" : value(point.size)] : []),
      ...(grouped ? [order[point.group] ?? ""] : []),
    ]),
  };
  const current = cursor.active === null ? undefined : points[cursor.active];
  const describe = (point: Point): string =>
    [point.name, grouped ? order[point.group] : "", `${names.x} ${value(point.x)}`, `${names.y} ${value(point.y)}`, size && point.size !== null ? `${names.size} ${value(point.size)}` : ""]
      .filter(Boolean)
      .join(", ");
  const legend = showLegend ?? (grouped && order.length > 1);
 
  return (
    <div data-slot="scatter-chart" className={cn("flex w-full min-w-0 flex-col gap-3", className)} {...props}>
      {legend ? <ChartLegend items={order.map((item, index) => ({ label: item, index }))} mark="rect" /> : null}
      <ChartContainer aspect={aspect ?? 4 / 3} height={height} table={table} announcement={cursor.keyboard && current ? describe(current) : ""}>
        {({ width, height: plotHeight }) => {
          if (points.length === 0) return <ChartEmpty>{emptyLabel}</ChartEmpty>;
          const xs = points.map((point) => point.x);
          const ys = points.map((point) => point.y);
          const lowX = Math.min(...xs, ...(zeroX ? [0] : []));
          const highX = Math.max(...xs, ...(zeroX ? [0] : []));
          const lowY = Math.min(...ys, ...(zeroY ? [0] : []));
          const highY = Math.max(...ys, ...(zeroY ? [0] : []));
          const top = 12;
          const bottom = 44;
          const probe = chartLinear(lowY, highY, [plotHeight - bottom, top]);
          const axisY = formatValue ?? axisNumberFormatter(Math.max(Math.abs(lowY), Math.abs(highY)), locale);
          const left = widestText(probe.ticks.map(axisY)) + 12;
          const right = 12;
          const sx = chartLinear(lowX, highX, [left, width - right], 80);
          const sy = probe;
          const axisX = formatValue ?? axisNumberFormatter(Math.max(Math.abs(lowX), Math.abs(highX)), locale);
          const sizes = points.flatMap((point) => (point.size === null ? [] : [Math.max(0, point.size)]));
          const reach = maxRadius ?? Math.min(28, Math.max(6, Math.min(width, plotHeight) / 12));
          const radius = scaleSqrt()
            .domain([0, Math.max(1e-9, ...sizes)])
            .range([size ? 2 : 4, size ? reach : 4]);
          const placed = points.map((point) => ({
            point,
            cx: sx.scale(point.x),
            cy: sy.scale(point.y),
            r: size ? radius(Math.max(0, point.size ?? 0)) : 4.5,
          }));
          const finder = Delaunay.from(
            placed,
            (item) => item.cx,
            (item) => item.cy,
          );
          const onPointerMove = (event: PointerEvent<SVGSVGElement>): void => {
            const box = event.currentTarget.getBoundingClientRect();
            const px = event.clientX - box.left;
            const py = event.clientY - box.top;
            const index = finder.find(px, py);
            const hit = placed[index];
            cursor.point(hit && Math.hypot(hit.cx - px, hit.cy - py) <= Math.max(24, hit.r + 8) ? index : null);
          };
          const shown = cursor.active === null ? undefined : placed[cursor.active];
          // Big bubbles behind small ones, so none is hidden.
          const drawOrder = size ? [...placed].sort((a, b) => b.r - a.r) : placed;
          return (
            <>
              <ChartSvg label={label} width={width} height={plotHeight} interactive {...cursor.svgProps} onPointerMove={onPointerMove}>
                {showGrid ? (
                  <>
                    <ChartGrid offsets={sy.ticks.map((tick) => sy.scale(tick))} from={left} to={width - right} />
                    <ChartGrid offsets={sx.ticks.map((tick) => sx.scale(tick))} from={top} to={plotHeight - bottom} vertical />
                  </>
                ) : null}
                <ChartAxis
                  side="left"
                  at={left - 8}
                  ticks={sy.ticks.map((tick) => ({
                    offset: sy.scale(tick),
                    label: axisY(tick),
                  }))}
                />
                <ChartAxis
                  side="bottom"
                  at={plotHeight - bottom + 6}
                  ticks={sx.ticks.map((tick) => ({
                    offset: sx.scale(tick),
                    label: axisX(tick),
                  }))}
                />
                <g aria-hidden="true" className="fill-muted-foreground">
                  <text x={(left + width - right) / 2} y={plotHeight - 4} textAnchor="middle">
                    {names.x}
                  </text>
                  <text x={left} y={top - 2} textAnchor="start" className="sr-only">
                    {names.y}
                  </text>
                </g>
                <g aria-hidden="true">
                  {drawOrder.map((item) =>
                    size ? (
                      <circle
                        key={item.point.row}
                        cx={item.cx}
                        cy={item.cy}
                        r={item.r}
                        className={cn(
                          chartSeries(item.point.group).fill,
                          "stroke-background opacity-75 transition-opacity duration-instant motion-reduce:transition-none",
                          shown && shown !== item && "opacity-35",
                        )}
                        strokeWidth={1.5}
                      />
                    ) : (
                      <ChartMark
                        key={item.point.row}
                        index={item.point.group}
                        x={item.cx}
                        y={item.cy}
                        radius={4.5}
                        className={cn("transition-opacity duration-instant motion-reduce:transition-none", shown && shown !== item && "opacity-45")}
                      />
                    ),
                  )}
                  {shown ? <circle cx={shown.cx} cy={shown.cy} r={shown.r + 3} fill="none" className="stroke-foreground" strokeWidth={2} /> : null}
                </g>
              </ChartSvg>
              {shown ? (
                <ChartTooltip
                  x={shown.cx}
                  y={shown.cy}
                  side={shown.cx > width / 2 ? "left" : "right"}
                  title={shown.point.name || (grouped ? order[shown.point.group] : undefined)}
                  rows={[
                    { label: names.x, value: value(shown.point.x) },
                    { label: names.y, value: value(shown.point.y) },
                    ...(size && shown.point.size !== null ? [{ label: names.size, value: value(shown.point.size) }] : []),
                    ...(grouped && shown.point.name
                      ? [
                          {
                            label: "",
                            value: order[shown.point.group] ?? "",
                            index: shown.point.group,
                            mark: "rect" as const,
                          },
                        ]
                      : []),
                  ]}
                />
              ) : null}
            </>
          );
        }}
      </ChartContainer>
    </div>
  );
}