I am trying to add a horizontal line to my graph, relative to the y-axis values, the problem is that they show up at the wrong positions.
The 2 lines should display at values 90 and 140 relative to the y-axis values.
The code I used to add the line is below:
if (before_meal !== null || after_meal !== null) {
svg.append("svg:line")
.attr("x1", 0)
.attr("x2", width)
.attr("y1", before_meal)
.attr("y2", before_meal)
.style("stroke", "rgb(189, 189, 189)");
svg.append("svg:line")
.attr("x1", 0)
.attr("x2", width)
.attr("y1", after_meal)
.attr("y2", after_meal)
.style("stroke", "rgb(189, 189, 189)");
}
Please see my working example here: JSFiddle
In your code you have this:
var y = d3.scale.linear()
.range([height, 0]);
This is returning a function y
which maps pixel space to your plot coordinate space.
So when you do:
.attr("y1", before_meal)
You are telling d3 to put a line at 90 "pixels". Instead use:
.attr("y1", y(before_meal))
Which tells d3 to convert 90 y axis units to the appropriate pixels.
Updated fiddle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With