Want to add a mouseover effect to dots on a scatter plot in d3.js? Create a voronoi diagram to increase the mouseover space around each point.
For more information, watch this talk.
xxxxxxxxxx
<html>
<head>
<style>
body {
margin: 0 auto;
display: table;
}
.voronoi path {
fill: #fff;
stroke: #000;
stroke-width: 1px;
}
</style>
</head>
<body>
<div class="chart"></div>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var margin = {top: 5, right: 5, bottom: 20, left: 20},
width = 450 - margin.left - margin.right,
height = 450 - margin.top - margin.bottom;
var svg = d3.select(".chart").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 + ")");
var x = d3.scaleLinear()
.range([0,width]);
var y = d3.scaleLinear()
.range([height,0]);
var xAxis = d3.axisBottom()
.scale(x);
var yAxis = d3.axisLeft()
.scale(y);
var voronoi = d3.voronoi()
.x(function(d) { return x(d.x); })
.y(function(d) { return y(d.y); })
.extent([[0, 0], [width, height]]);
var voronoiGroup = svg.append("g")
.attr("class", "voronoi");
d3.csv("data.csv", types, function(error, data){
x.domain(d3.extent(data, function(d){ return d.x; }));
y.domain(d3.extent(data, function(d){ return d.y; }));
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
svg.selectAll(".point")
.data(data)
.enter().append("circle")
.attr("class", "point")
.attr("r", 3)
.attr("cx", function(d){ return x(d.x); })
.attr("cy", function(d){ return y(d.y); });
voronoiGroup.selectAll("path")
.data(voronoi(data).polygons())
.enter().append("path")
.attr("d", function(d) { return d ? "M" + d.join("L") + "Z" : null; })
})
function types(d){
d.x = +d.x;
d.y = +d.y;
return d;
}
</script>
</body>
</html>
https://d3js.org/d3.v4.min.js