var svg = d3.select("body").append("svg")
.attr("width", 500)
.attr("height", 200);
var color = d3.scaleOrdinal(d3.schemeCategory10);
var thisYear;
var line = d3.line()
.x(d => scales[thisYear](d.x))
.y(d => yScale(d.y))
.curve(d3.curveMonotoneX);
var years = [2013, 2014, 2015, 2016, 2017];
var data = [];
years.forEach((d, i) => {
data.push({
year: d,
points: []
});
for (var j = 0; j < 12; j++) {
data[i].points.push({
y: Math.random() * 80 + 20,
x: new Date(d, j)
})
}
});
var scales = {};
var yScale = d3.scaleLinear()
.domain([0, 100])
.range([170, 30]);
years.forEach(d => {
scales["scale" + d] = d3.scaleTime()
.domain([new Date(+d, 0, 1), new Date(+d, 11, 31)])
.range([30, 470]);
});
var paths = svg.selectAll("foo")
.data(data)
.enter()
.append("path");
paths.attr("stroke", (d, i) => color(i))
.attr("d", d =>{
thisYear = "scale" + d.year;
return line(d.points);
})
.attr("fill", "none");
var xAxis = d3.axisBottom(scales.scale2017).tickFormat(d=>d3.timeFormat("%b")(d));
var yAxis = d3.axisLeft(yScale);
var gX = svg.append("g").attr("transform", "translate(0,170)").call(xAxis);
var gY = svg.append("g").attr("transform", "translate(30,0)").call(yAxis);
<script src="https://d3js.org/d3.v4.js"></script>
var paths = svg.selectAll("foo")
行的引号内,例如“foo”,本质上可以是任何东西且图表仍然有效,那么selectAll
的意义是什么?这不是我见过的唯一例子。其次,enter()
确切地做什么?最后,我欣赏这个例子。我没有考虑到创建多个比例尺,这是一个非常干净和明显正确的方法。 - DanCat