简体   繁体   中英

Y-axis should display whole number values from 0 to maxYValue on d3.js without repetition

I want to show values like [0,1,2,..., maxYValue] instead of [0, 0.5, 1, 1.5... maxYValue].

var y = d3.scaleLinear()
      .range([height - margin, 0])
      .domain([0, this.maxYValue]); //maxYValue can be any whole. number

Original:

d3.axisLeft(y).ticks(5).tickSize(-width + margin)

Modified:

d3.axisLeft(y).ticks(5).tickSize(-width + margin).tickFormat("f")

After using tickFormat("f"), it starts displaying the y-axis values like [0,0,0, 1, 1, 1]. It is rounding off the values. But, I want to set a step value to the y-axis values to get the data like [0,1,2,3,.., maxYValue]

If you simply wants all integers up to the maxYValue , instead of using axis.tickFormat on the auto-generated ticks just use d3.range to generate an array based on the scale's domain, and pass that to axis.tickValues :

d3.axisLeft(y).tickValues(d3.range(y.domain()[0], y.domain()[1] + 1, 1));

For instance:

 const y = d3.scaleLinear().domain([0, 12]); console.log(d3.range(y.domain()[0], y.domain()[1] + 1, 1))
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.3.0/d3.min.js"></script>

If maxYValue is not the last value in the scale's domain, just use that variable instead.

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