Public
Edited
Jul 25, 2023
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
{
now;
updateCars();

const runningPlot = Plot.plot({
x: { nice: true, domain: [-1.1, 1.1] },
y: { nice: true, domain: [-1.1, 1.1] },
color: {
legend: true,
domain: [0, 1.0],
nice: true
},
aspectRatio: 1.0,
grid: true,
marks: [
Plot.frame(),
Plot.dot(cars, { x: "x", y: "y", fill: "speedInAng", r: 10 }),
Plot.text(cars, { x: "x", y: "y", text: "idx" }),
Plot.text(cars, { x: "x", y: "y", text: "speedInAng", dx: 10, dy: 10 })
]
});

const boxPlot = Plot.plot({
x: { nice: true },
y: { nice: true, domain: [0, 1.0] },
color: {
legend: true,
domain: [0, 1.0]
},
grid: true,
marks: [
Plot.frame(),
Plot.barY(cars, { x: "idx", y: "speedInAng", fill: "speedInAng" }),
Plot.ruleY([d3.mean(cars, (d) => d.speedInAng)])
]
});

return htl.html`
<div style="display: flex">
${runningPlot}
${boxPlot}
</div>
`;
}
Insert cell
cars
Type Table, then Shift-Enter. Ctrl-space for more options.

Insert cell
cars = {
const cars = [],
angScale = d3.scaleLinear().domain([0, numCars]).range([0, 360]);

for (let i = 0; i < numCars; ++i) {
cars.push({
idx: i,
nextIdx: (i + 1) % numCars,
ang: angScale(i),
speedInAng: 0.1
});
}

cars.map((d) => {
Object.assign(d, ang2xy(d.ang));
});

return cars;
}
Insert cell
updateCars = () => {
cars.map((d) => {
const dist =
cars[d.nextIdx].ang > d.ang
? cars[d.nextIdx].ang - d.ang
: 360 + cars[d.nextIdx].ang - d.ang,
distInNeed = (d.speedInAng * (d.speedInAng / diffSpeedAngle)) / 2;

if (distInNeed > dist) {
d.speedInAng -= diffSpeedAngle;
} else {
d.speedInAng += diffSpeedAngle / 5;
}

if (d.speedInAng > 2.0) d.speedInAng = 2.0;
if (d.speedInAng < diffSpeedAngle) d.speedInAng = diffSpeedAngle;

d.ang += d.speedInAng;
Object.assign(d, ang2xy(d.ang));
});
}
Insert cell
ang2xy = (ang) => {
const x = cos(ang),
y = sin(ang);

return { x, y };
}
Insert cell
cos = (ang) => {
return Math.cos(angle2radius(ang));
}
Insert cell
sin = (ang) => {
return Math.sin(angle2radius(ang));
}
Insert cell
angle2radius = (ang) => {
return (ang / 180) * Math.PI;
}
Insert cell
d3 = require("d3")
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more