# Linked scatterplot brush

Draw a box over seven samples arranged by density and lightness. Enclosed dots and their table rows light up together.

## Try it

Choose Low density to select A, B and C, then drag inside the box to the right to change the highlighted rows.

## Interaction details

Check both axes and include points on the boundary. Clearing removes the highlight from dots and rows together.

## Platform controls

- iOS · Drag on empty paper to draw, then inside the box to move it. The density buttons also select ranges.
- Android · Drag on empty paper to draw, then inside the box to move it. The density buttons also select ranges.
- PC · Focus the plot. Arrows move the box, Shift + arrows resize it, and Escape clears it.

## Where to use it

Inspect individual records within two simultaneous value ranges.

## Implementation prompt

> Allow drawing and moving a rectangular brush. Highlight the matching table rows, keeping the box size fixed during a move.

## Sources and credits

[D3 · Brush](<https://d3js.org/d3-brush>)

## Standalone HTML

Save the code below as an HTML file and open it in your browser. The example works offline.

```html
<!doctype html>
<html lang="en" data-motion-locales="inline">
<head><script>if(new URLSearchParams(location.search).get('reduce')==='1')document.documentElement.classList.add('motion-reduced');</script><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>잉크 견본 분포 · MotionLab</title><style>
*{box-sizing:border-box} :root{color-scheme:light;font:15px/1.45 system-ui,-apple-system,"Segoe UI",sans-serif;color:var(--ink);background:var(--bg)}body{margin:0;min-height:100svh;display:grid;align-content:center;padding:clamp(10px,2.4vw,25px)}main{width:min(100%,760px);min-width:0;margin:auto}header{display:flex;align-items:baseline;justify-content:space-between;gap:8px;flex-wrap:wrap;margin-bottom:9px}h1{margin:0;font-size:clamp(21px,4vw,32px);line-height:1.15;letter-spacing:-.045em}header small,output,.mono{font:650 12px/1.4 ui-monospace,monospace}header small{color:var(--muted)}.board{border:1px solid var(--line);overflow:hidden;border-radius:8px;background:var(--paper)}svg{display:block;width:100%}button{appearance:none;display:inline-flex;justify-content:center;align-items:center;min-height:40px;color:var(--ink);background:var(--paper);border:1px solid var(--line);border-radius:5px;padding:5px 12px;font:650 13px/1.2 inherit;font-family:inherit;font-size:13px;font-weight:650;cursor:pointer;touch-action:manipulation}button:focus-visible,input:focus-visible,[tabindex]:focus-visible{outline:3px solid #d96326;outline-offset:2px}button:disabled{opacity:.55;cursor:default}.controls{display:flex;gap:6px;align-items:center;flex-wrap:wrap;margin-top:9px}.controls output{margin-inline-start:auto}p{margin:8px 0 0;color:var(--muted);font-size:13px;line-height:1.4;word-break:keep-all;overflow-wrap:anywhere}input[type=range]{accent-color:var(--accent);min-width:65px;cursor:pointer}svg text{font-family:inherit}.drag{touch-action:none;user-select:none;-webkit-user-select:none}.sr-only{position:absolute;clip-path:inset(50%);width:1px;height:1px;overflow:hidden;white-space:nowrap}
:root{--bg:#e6eee6;--paper:#f7f9ed;--ink:#153c35;--muted:#3a5b4e;--line:#95aa99;--accent:#287967}.board{display:grid;grid-template-columns:1fr minmax(144px,26%)}#plot{align-self:center;cursor:crosshair}.sheet{border-left:1px solid var(--line);padding:8px 10px;align-content:center}table{border-collapse:collapse;width:100%;font:600 12px/1.3 ui-monospace,monospace;font-variant-numeric:tabular-nums}th,td{text-align:right;padding:4px 3px}th:first-child,td:first-child{text-align:left}thead{font-size:10px;color:var(--muted)}td{border-top:1px solid #cad7c8}tr[data-on=true]{background:#d1e5c0;color:#113e30}td b{display:inline-block;width:8px;height:8px;border-radius:50%;background:var(--tone);margin-right:4px}#rect{fill:#49a582;fill-opacity:.11;stroke:#24745c;stroke-width:1.5;stroke-dasharray:5 3}#dots text{font-size:11px;fill:#243e32;font-weight:700}#dots circle{stroke:#fcfff2;stroke-width:1.5}.point[data-on=true] .ring{stroke:#245e49;stroke-width:2}.point .ring{fill:none;stroke:transparent}#ticks{fill:#516557;font:11px ui-monospace,monospace}.caption{display:flex;justify-content:space-between;padding:3px 9px;font:650 12px/1.3 system-ui,sans-serif}.axis-note{margin-top:4px}@media(max-width:530px){.board{grid-template-columns:1fr}.sheet{border-left:0;border-top:1px solid var(--line);padding:3px 8px}th,td{padding:2px 6px}table{font-size:11px}.controls output{margin-inline-start:0}}
</style></head>
<body><main><header><h1 data-text="heading"></h1><small data-text="label"></small></header>
<div class="board"><div><div class="caption"><span data-text="light"></span><span>↑ %</span></div>
<svg class="drag" id="plot" viewBox="0 0 440 202" role="group" tabindex="0" data-label="plot"><g id="ticks"></g><rect id="rect" rx="2"/><g id="dots" pointer-events="none"></g></svg>
<div class="caption"><span>0 → 100%</span><span data-text="density"></span></div></div>
<div class="sheet"><table><thead><tr><th data-text="sample"></th><th data-text="density"></th><th data-text="light"></th></tr></thead><tbody id="rows"></tbody></table></div></div>
<div class="controls"><button id="left" data-text="left"></button><button id="right" data-text="right"></button><button id="clear" data-text="clear"></button><output id="count" aria-live="polite"></output></div>
<p data-text="hint"></p></main><script>
'use strict';
const strings={"ko":{"heading":"잉크 견본 분포","label":"산점도와 표","hint":"빈 곳을 끌어 영역을 그리고, 사각형 안을 끌어 옮기세요. 차트에 초점을 두면 방향키로 이동하고 Shift와 방향키로 크기를 바꿀 수 있습니다.","plot":"잉크 견본 산점도","density":"농도","light":"명도","sample":"견본","left":"옅은 쪽","right":"짙은 쪽","clear":"선택 해제","count":"선택"},"en":{"heading":"Ink sample atlas","label":"Scatterplot & table","hint":"Drag on empty paper to draw a box. Drag inside it to move it. Focus the chart and use the arrows to move, or Shift + arrows to resize.","plot":"Ink sample scatterplot","density":"Density","light":"Lightness","sample":"Sample","left":"Low density","right":"High density","clear":"Clear","count":"Selected"},"es":{"heading":"Atlas de muestras de tinta","label":"Gráfico y tabla","hint":"Arrastra en una zona vacía para dibujar un cuadro y dentro para moverlo. Enfoca el gráfico y usa las flechas para moverlo o Mayús + flechas para ajustar su tamaño.","plot":"Gráfico de puntos de tinta","density":"Densidad","light":"Claridad","sample":"Muestra","left":"Baja densidad","right":"Alta densidad","clear":"Borrar selección","count":"Selección"},"zh-Hans":{"heading":"油墨样本图谱","label":"散点图与表格","hint":"在空白处拖出选框，拖动框内可移动。聚焦图表后可用方向键移动，用 Shift 加方向键调整大小。","plot":"油墨样本散点图","density":"浓度","light":"明度","sample":"样本","left":"低浓度","right":"高浓度","clear":"清除选择","count":"已选"}};
const query=new URLSearchParams(location.search);
const lang=query.get('lang')||document.documentElement.lang||'ko';
const t=strings[lang]||strings.ko;
document.documentElement.lang=strings[lang]?lang:'ko';
document.title=t.heading+' · MotionLab';
const $=id=>document.getElementById(id);
for(const el of document.querySelectorAll('[data-text]')) el.textContent=t[el.dataset.text];
for(const el of document.querySelectorAll('[data-label]')) el.setAttribute('aria-label',t[el.dataset.label]);
const media=matchMedia('(prefers-reduced-motion: reduce)');
const reduced=()=>query.get('reduce')==='1'||document.documentElement.classList.contains('motion-reduced')||media.matches;
const NS='http://www.w3.org/2000/svg';
function shape(tag,attrs,parent){const node=document.createElementNS(NS,tag); for(const [k,v] of Object.entries(attrs))node.setAttribute(k,v);parent.append(node);return node;}
function coords(svg,e){const p=new DOMPoint(e.clientX,e.clientY).matrixTransform(svg.getScreenCTM().inverse());return {x:p.x,y:p.y};}
const clamp=(n,min,max)=>Math.min(max,Math.max(min,n));
const plot=$('plot'), bounds={x:30,y:10,w:394,h:166};
const samples=[['A',12,30,'#a87955'],['B',28,70,'#9e9a4f'],['C',41,43,'#587e59'],['D',55,84,'#d68670'],['E',65,36,'#41827e'],['F',79,61,'#655490'],['G',90,16,'#294452']];
for(let i=0;i<=4;i++){const x=bounds.x+bounds.w*i/4,y=bounds.y+bounds.h*i/4;shape('path',{d:'M'+x+' 10V176 M30 '+y+'H424',stroke:'#cbd8c6','stroke-dasharray':i===0?'0':'2 4'},$('ticks'));shape('text',{x,y:194,'text-anchor':'middle'},$('ticks')).textContent=i*25;}
const points=samples.map(([id,density,light,color])=>{
  const x=bounds.x+bounds.w*density/100,y=bounds.y+bounds.h*(1-light/100);
  const g=shape('g',{class:'point',transform:'translate('+x+' '+y+')'},$('dots'));
  shape('circle',{class:'ring',r:10},g);shape('circle',{r:6.5,fill:color},g);shape('text',{x:11,y:-6},g).textContent=id;
  const row=document.createElement('tr');row.style.setProperty('--tone',color);row.innerHTML='<td><b></b>'+id+'</td><td>'+density+'%</td><td>'+light+'%</td>';$('rows').append(row);
  return {id,x,y,g,row};
});
let box=null,drag=null;
function setBox(p){
  box=p;const visible=!!box;$('rect').style.display=visible?'':'none';
  if(visible)for(const key of ['x','y','width','height'])$('rect').setAttribute(key,p[key]);
  const selected=[];for(const {x,y,id,g,row} of points){
    const hit=!!p&&x>=p.x&&x<=p.x+p.width&&y>=p.y&&y<=p.y+p.height;
    row.dataset.on=g.dataset.on=String(hit);
    if(hit)selected.push(id);
  }
  plot.dataset.ids=selected.join(',');$('count').textContent=t.count+' '+selected.length+' / '+points.length;
}
function preset(high){setBox({x:high?236:40,y:44,width:172,height:110});}
$('left').onclick=()=>preset(false);$('right').onclick=()=>preset(true);$('clear').onclick=()=>setBox(null);
function constrained(e){const p=coords(plot,e);return{x:clamp(p.x,30,424),y:clamp(p.y,10,176)};}
function move(px,py,original){setBox({...original,x:clamp(original.x+px,30,424-original.width),y:clamp(original.y+py,10,176-original.height)});}
plot.onpointerdown=e=>{if(drag||e.button!==0)return;const p=constrained(e);const inside=box&&p.x>=box.x&&p.x<=box.x+box.width&&p.y>=box.y&&p.y<=box.y+box.height;
  drag={id:e.pointerId,start:p,move:inside,snapshot:box&&{...box}};plot.setPointerCapture(e.pointerId);
  if(!inside)setBox({x:p.x,y:p.y,width:0,height:0});
};
plot.onpointermove=e=>{if(!drag||drag.id!==e.pointerId)return;const p=constrained(e),s=drag.start;
  if(drag.move)move(p.x-s.x,p.y-s.y,drag.snapshot);else setBox({x:Math.min(s.x,p.x),y:Math.min(s.y,p.y),width:Math.abs(s.x-p.x),height:Math.abs(s.y-p.y)});
};
plot.onpointerup=e=>{if(!drag||drag.id!==e.pointerId)return;if(!drag.move&&(box.width<3||box.height<3))setBox(null);drag=null;};
plot.onpointercancel=e=>{if(drag?.id===e.pointerId){setBox(drag.snapshot);drag=null;}};
plot.onkeydown=e=>{if(e.key==='Escape'){setBox(null);return;}
  const step={ArrowLeft:[-8,0],ArrowRight:[8,0],ArrowUp:[0,-8],ArrowDown:[0,8]}[e.key];if(!step)return;e.preventDefault();if(!box)preset(false);
  if(e.shiftKey)setBox({...box,width:clamp(box.width+step[0],5,424-box.x),height:clamp(box.height+step[1],5,176-box.y)});else move(...step,box);
};
preset(false);
</script></body></html>
```
