简体   繁体   中英

How to make axis “smart” and “flexible” so that the starting/end points on axis are sensible in D3 V4?

I have the following Line Graph (CodePen) and as you can see, the Y-Axis isn't very smart. It begins from 0 when it should begin from somewhere near 2200 .

My guess was that this would be to do with scales:

// set the ranges
var x = d3.scalePoint().range([0, width]);
var y = d3.scaleLinear().range([height, 0]);

But I tried all sorts to get this to behave the "smart" and "flexible" way and couldn't.

How can I make the axis smarter? So if tomorrow I feed the chart a different set of data that starts at 150 , the code is smart enough to draw relevant axis values.

If you don't want the Y axis starting at 0 , you shouldn't set the lower value in the domain to zero, as you did:

y.domain([0, d3.max(result, function(d) { 
    return d.consumption;
})]);

If you want the Y axis to start next to the minimum value, you should use:

y.domain([d3.min(result, function(d) {
    return d.consumption; })*0.975,
d3.max(result, function(d) { 
    return d.consumption; })*1.025
]);

Here, the numbers 0.975 and 1.025 are just values to make the axis going a little bit below and after the minimum and maximum values, respectively. You can change them or remove them.

Here is your updated CodePen: http://codepen.io/anon/pen/EgOBvO?editors=0010

PS: while in a bar chart it's highly recommended to always use a zero baseline for the Y axis, there is no problem using a non-zero baseline for the Y axis in a time series (line chart).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM