Home > Blockchain >  D3 linear scale between two numbers
D3 linear scale between two numbers

Time:07-22

I would like to generete scale with d3 (v7) between 180 and 360 (inclusive) with 4 ticks. Actually i need a scale with values/ticks: 180, 240, 300 and 360.

I tired this:

d3.scaleLinear()
    .domain([180, 360]).ticks(4)

but I get:

[200, 250, 300, 350]

Does anyone know how to generate scale to get ticks mentioned above [180, 240, 300, 360]

EDITED

I try to generate scale/axis for some chart:

const yScale = d3.scaleLinear()
      .domain([180, 360])
      .range([containerHeight, 0]);

const yAxis = d3.axisLeft(yScale)
      .ticks(4);

svg.append('g')
      .call(yAxis);

As you can see the scale in axis is wrong. Instead of 180, 240, 300 and 300 I get 200, 250, 300 and 350

enter image description here

CodePudding user response:

If you just want an array with values given a start, end and count, you don't need d3 for that.

const ticks = 4;
const start = 180;
const end = 360;

console.log(Array.from({length: ticks}, (_, i) => i *  (end - start) / (ticks - 1)   start))

This creates the array [180, 240, 300, 360] so just plug that in instead of the d3 code as I've done below via tickValues...

let svg = d3.select("body")
                .append("svg")
                .attr("width", 300)
                .attr("height", 150);
                
const yScale = d3.scaleLinear()
      .domain([180, 360])
      .range([100, 0]);

const yAxis = d3.axisLeft(yScale)
      .tickValues(Array.from({length: 4}, (_, i) => i *  60   180));

svg.append('g').attr("transform", "translate(50,10)")
      .call(yAxis);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

  • Related