Nathanael Farley
Nathanael Farley

Reputation: 400

How to get automatically generated tickValues for d3 axis

I have a axis with automatically generated ticks:

var yAxisRight = d3.axisRight(yScale)
var yAxisRightG = g.append("g")
    .call(yAxisRight);

// What to call here
var yAxisRightTickValues = ???

Naively I would think calling something like yAxisRight.tickValues() would give me the values, but when they are automatically generated this returns null.

How can I get the tickValues that have been automatically made by d3 (version 4)?

Upvotes: 1

Views: 1211

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102174

If you have a continuous scale, you can use scale.ticks() to get the ticks passed to the axis generator.

In this demo, the console.log shows the ticks of each axis:

var scale = d3.scaleLinear()
  .range([20, 280]);

[100, 50, 210, 350].forEach(function(d, i) {
  scale.domain([0, d]);
  d3.axisBottom(scale)(d3.select("svg").append("g").attr("transform", "translate(0,"
  + (10 + 25 * i) + ")"));
  console.log("the scale " + i + " has these ticks: " + scale.ticks())
})
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg>

Upvotes: 2

Related Questions