Creating a categorical line chart in D3.js (V4)

谁都会走 提交于 2019-12-06 11:33:29

You want a categorical scale, that's right, but you don't want an ordinal scale here.

There was a lot of changes from v3 to v4. In v3, you could set .rangeBands, .rangeRoundBands, .rangePoints and .rangeRoundPoints to your ordinal scale, which therefore could accept an continuous range. Not anymore: in D3 v4 you have the brand new scaleBand and scalePoint.

In v4, in a regular ordinal scale (which is scaleOrdinal):

If range is specified, sets the range of the ordinal scale to the specified array of values. The first element in the domain will be mapped to the first element in range, the second domain value to the second range value, and so on. If there are fewer elements in the range than in the domain, the scale will reuse values from the start of the range. (emphases mine)

So, in an scaleOrdinal, the range need to have the same length (number of elements) of the domain.

That being said, you want a point scale (scalePoint) here. Band scales and point scales...

...are like ordinal scales except the output range is continuous and numeric. (emphasis mine)

Check this snippet, look at the console and compare the two scales:

var destinations = ["foo", "bar", "baz", "foobar", "foobaz"];

var scale1 = d3.scaleOrdinal()
	.range([0, 100])
	.domain(destinations);
	
var scale2 = d3.scalePoint()
	.range([0, 100])
	.domain(destinations);
	
destinations.forEach(d=>{
console.log(d + " in an ordinal scale: " + scale1(d) + " / in a point scale: " + scale2(d))
})
<script src="https://d3js.org/d3.v4.min.js"></script>

Regarding your y-axis problem:

Set the domain of the y scale before calling the axis. So, instead of this:

svg.append("g")
    .attr("class", "y axis").call(yAxis);

y.domain([d3.min(data, function(d){
    return d.PassengersIn;
}), d3.max(data, function(d){
    return d.PassengersIn;
})]);

Change the order:

y.domain([d3.min(data, function(d){
    return d.PassengersIn;
}), d3.max(data, function(d){
    return d.PassengersIn;
})]);//set the domain first!

svg.append("g")
    .attr("class", "y axis").call(yAxis);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!