I am utilizing d3.js to display data in my Ionic app. I have a touch event that allows me to move a line and retrieve the coordinates where it intersects with my chart. While I can easily obtain the x-coordinate representing the date, I am struggling to get the continuous y-coordinates. Currently, I can find discrete y-coordinates by looping through the data array but I need the values "in-between". Below is how I am attempting this (I trigger the function drawChart()
when the View loads)
private drawChart() {
let width = 900 - this.margin.left - this.margin.right;
let height = 500 - this.margin.top - this.margin.bottom;
/*
Data is structured as: [{date: , value: }]
*/
let data = this.data;
let svg = d3.select("#chart")
.append("svg")
.attr("width", '100%')
.attr("height", '100%')
.attr('viewBox','0 0 900 500')
.append("g")
.attr("transform", "translate(" + this.margin.left + "," + this.margin.top + ")");
let x = d3Scale.scaleTime().range([0, width]);
let y = d3Scale.scaleLinear().range([height, 0]);
x.domain(d3Array.extent(this.data, (d) => d.date ));
y.domain(d3Array.extent(this.data, (d) => d.value ));
svg.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0,"+ height + ")")
.call(d3Axis.axisBottom(x));
svg.append("g")
.attr("class", "axis axis--y")
.call(d3Axis.axisLeft(y));
let line = d3Shape.line()
.x((d) => x(d.date))
.y((d) => y(d.value));
let path = g.append("path")
.datum(this.data)
.attr("class", "line")
.attr("d", line);
let cursorLine = svg
.append("line")
.attr("stroke-width",3)
.attr("stroke","black")
.style("opacity", 0);
svg.on("touchstart", touched);
svg.on("touchmove", touched);
function touched() {
let d = d3.touches(this);
svg
.selectAll("line")
.data(d)
.style("opacity", 1);
svg
.selectAll("line")
.attr("x1", (d) => d[0])
.attr("x2", (d) => d[0])
.attr("y1", 0)
.attr("y2", height);
let formatTime = d3.timeFormat("%Y-%m-%d");
let dateVal = formatTime(xScale.invert(d[0][0]));
let val = 0;
data.forEach(d => {
if(formatTime(d.date) === dateVal) {
val = d.value;
}
})
}
}
If you have any suggestions on how I can attain the y-values continuously while sliding the cursor line, please share! Any help would be greatly appreciated.