Polis2024-08-20
2024-08-19
The data returned by this API as initData
code:js
pca = JSON.parse(initData"pca") // Create id->(x,y) correspondence
const idToCoordinates = {};
ids.forEach((id, index) => {
};
});
// Create data for each cluster
data = []
const clusterData = groupClusters.forEach((cluster, index) => {
cluster.members.forEach((id)=>{
data.push({
cluster: index,
});
});
});
// SVG Settings
const width = 600;
const height = 400;
const margin = {top: 20, right: 20, bottom: 30, left: 40};
const svg = d3.select("#scatter-plot")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", translate(${margin.left},${margin.top}));
// Scale settings
const xScale = d3.scaleLinear()
.domain(d3.extent(data, d => d.x))
const yScale = d3.scaleLinear()
.domain(d3.extent(data, d => d.y))
// Add Axis
svg.append("g")
.attr("transform", translate(0,${height}))
.call(d3.axisBottom(xScale));
svg.append("g")
.call(d3.axisLeft(yScale));
// Color Scale Settings
const colorScale = d3.scaleOrdinal(d3.schemeCategory10);
// Scatter plot
svg.selectAll("circle")
.data(data)
.enter()
.append("circle")
.attr("cx", d => xScale(d.x))
.attr("cy", d => yScale(d.y))
.attr("r", 5)
.style("fill", d => colorScale(d.cluster));
// Add label
svg.selectAll("text")
.data(data)
.enter()
.append("text")
.attr("x", d => xScale(d.x) + 10)
.attr("y", d => yScale(d.y))
.text(d => d.label)
.style("font-size", "12px");
// Convex Hull generation function
console.log("hello");
// Group data by cluster
const clusters = d3.group(data, d => d.cluster);
// Convex Hull Drawing
const hull = d3.polygonHull;
clusters.forEach((points, cluster) => {
if (hullPoints) {
svg.append("path")
.datum(hullPoints)
.attr("d", d => M${d.join("L")}Z)
.attr("fill", colorScale(cluster))
.attr("fill-opacity", 0.2)
.attr("stroke", colorScale(cluster))
.attr("stroke-width", 2);
}
});
https://scrapbox.io/files/66c419608324bc001c157fa8.png
https://scrapbox.io/files/66c41962d33e62001c128205.png
They can be made in the same cluster shape, just upside down.
---
This page is auto-translated from /nishio/Polis2024-08-20 using DeepL. If you looks something interesting but the auto-translated English is not good enough to understand it, feel free to let me know at @nishio_en. I'm very happy to spread my thought to non-Japanese readers.