Published
Edited
Feb 14, 2021
1 star
Insert cell
Insert cell
Insert cell
import {kmeans} from "@spond/k-means-clustering-algorithm"
Insert cell
Insert cell
data = formatData(cars)
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
// scatterplot code based on https://observablehq.com/@d3/scatterplot
chart = {
kmeans(data, clusters)
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height])
.attr("max-width", myWidth);

xScale.domain(d3.extent(data, d => d.x)).nice()
yScale.domain(d3.extent(data, d => d.y)).nice()
svg.append("g")
.call(xAxis)
.append("text")
.attr("x", myWidth)
.attr("y", margin.bottom - 4)
.attr("fill", "currentColor")
.attr("text-anchor", "end")
.text(x)

svg.append("g")
.call(yAxis)
.append("text")
.attr("x", -margin.left)
.attr("y", 10)
.attr("fill", "currentColor")
.attr("text-anchor", "start")
.text(y)

svg.append("g")
.attr("stroke-width", 1.5)
.attr("fill", "none")
.selectAll("circle")
.data(data)
.join("circle")
.attr("cx", d => xScale(d.x))
.attr("cy", d => yScale(d.y))
.attr("stroke", d => color(d.cluster))
.attr("r", 3);

return svg.node();
}
Insert cell
Insert cell
myWidth = Math.min(height, width);
Insert cell
height = 450
Insert cell
margin = ({top: 25, right: 20, bottom: 35, left: 40})
Insert cell
xScale = d3.scaleLinear()
.range([margin.left, myWidth - margin.right])
Insert cell
yScale = d3.scaleLinear()
.range([height - margin.bottom, margin.top])
Insert cell
xAxis = g => g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(xScale).ticks(width / 80))
Insert cell
yAxis = g => g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(yScale))
Insert cell
color = d3.scaleOrdinal(d3.schemeTableau10);
Insert cell
Insert cell
function formatData (local_data) {
let new_data = JSON.parse(JSON.stringify(local_data))
new_data.forEach(d => {
d.x = d[x]
d.y = d[y]
})
return new_data
}
Insert cell
Insert cell
import {Range, Select} from "@observablehq/inputs"
Insert cell
d3 = require("d3@6")
Insert cell
Insert cell
cars = require('@observablehq/cars')
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