最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Adding a horizontal line to d3 graph displays at the wrong value - Stack Overflow

programmeradmin3浏览0评论

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

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

Share Improve this question asked Jan 14, 2015 at 20:10 achabacha322achabacha322 65111 silver badges32 bronze badges 1
  • feel free to change the css to colors you like.be creative – achabacha322 Commented Jan 14, 2015 at 20:20
Add a ment  | 

1 Answer 1

Reset to default 14

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.

发布评论

评论列表(0)

  1. 暂无评论