Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a horizontal line to d3 graph displays at the wrong value

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

like image 346
achabacha322 Avatar asked Jan 14 '15 20:01

achabacha322


Video Answer


1 Answers

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.

like image 82
Mark Avatar answered Oct 03 '22 15:10

Mark