I have written the following code snippets to create a legend for a scatter plot.
Basically, it is a simple example that uses Susie Lu’s D3-legend module to create a legend for a scatter plot.
The webpage, however, shows nothing.
What am I missing?
What am I doing wrong?
my HTML code:
<html>
<head>
<title>D3 Legend</title>
<link rel="stylesheet" href="style-sheet.css">
</head>
<body>
<script src="https://d3js.org/d3.v7.min.js"></script>
<script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3-legend/2.25.6/d3-legend.min.js"></script>
<script src="data-script.js"></script>
<svg id="scatterplot"></svg>
<div id="legend"></div>
</body>
</html>
my CSS code:
.legend {
font-family: Arial, sans-serif;
font-size: 12px;
}
my JavaScript code:
// Set up the scatter plot
var margin = { top: 20, right: 20, bottom: 30, left: 40 };
var width = 600 - margin.left - margin.right;
var height = 400 - margin.top - margin.bottom;
var x = d3.scaleLinear()
.range([0, width]);
var y = d3.scaleLinear()
.range([height, 0]);
var color = d3.scaleSequential(d3.interpolateViridis);
var svg = d3.select("#scatterplot")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.csv("data.csv", function (error, data) {
if (error) throw error;
data.forEach(function (d) {
d.x = +d.x;
d.y = +d.y;
});
x.domain(d3.extent(data, function (d) { return d.x; })).nice();
y.domain(d3.extent(data, function (d) { return d.y; })).nice();
color.domain(d3.extent(data, function (d) { return d.z; }));
svg.selectAll(".dot")
.data(data)
.enter().append("circle")
.attr("class", "dot")
.attr("r", 3.5)
.attr("cx", function (d) { return x(d.x); })
.attr("cy", function (d) { return y(d.y); })
.style("fill", function (d) { return color(d.z); });
});
// Set up the legend
var legend = d3.legendColor()
.labelFormat(d3.format(".2f"))
.title("Z Value")
.scale(color);
d3.select("#legend")
.append("svg")
.attr("class", "legend")
.call(legend);