Reputation: 21621
Hello I'm trying to understand this example and this other example to add grid lines to a stacked area.
tiksArray = [1900, 1950, 2000, 2010];
keys = ["Amanda", "Ashley", "Betty", "Deborah"];
// Add X axis
const dX = d3.extent(nbrOfBabies, d => d.year);
const x = d3.scaleLinear()
.domain(dX)
.range([0, this.width]);
svg.append("g")
.attr("class", "grid")
.attr("transform", `translate(0,${this.height})`)
.call(this.make_x_gridlines(x)
.tickSize(-this.height)
.tickFormat(null)
);
// gridlines in x axis function
make_x_gridlines(x) {
const bttm = d3.axisBottom(x)
.tickValues(this.tiksArray);
return bttm;
}
I'm getting this graph. I'd like to know the X value of those ticks, i.e. 1900, 1950, 2000. I'd like to know where each line start so I can add a legend for each column.
Thanks for helping.
Upvotes: 2
Views: 62
Reputation: 102174
In D3, the axis generator uses the passed scale for positioning the ticks. Therefore, all you need to do is passing those values in your tiksArray
to the same scale (in your case, x
).
Here is a very basic demo:
const ticksArray = [1900, 1950, 2000, 2010];
const svg = d3.select("svg")
const x = d3.scaleLinear()
.domain([1880, 2020])
.range([50, 450]);
svg.append("g")
.attr("transform", `translate(0,${100})`)
.call(d3.axisBottom(x)
.tickValues(ticksArray)
.tickSizeInner(-100)
);
ticksArray.forEach(d => {
console.log("The SVG position of the tick " + d + " is: " + x(d))
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg width="500" height="200"></svg>
Upvotes: 1