Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a fixed range vertical line to a D3.js chart

I am trying to add a vertical line on an existing line chart. My data looks likes this - column PC is a calculated percentage - and the vertical line should extend from 0 to 100 percent on the chart:

var data = [
{"Month":"2014-06" , "PC" : 38 , "items" : 72 }, 
{"Month":"2014-07" , "PC" : 33 , "items" : 68 }, 
{"Month":"2014-08" , "PC" : 28 , "items" : 80 }, 
{"Month":"2014-09" , "PC" : 16 , "items" : 93 }
]

I build the y axis fine as follows where I have forced the range to be 0 to 100, since the data values do not actually cover the full range:

var y = d3.scale.linear()
.range([height, 0], 0.5);
y.domain([0, 100]);
var yAxis = d3.svg.axis().scale(y).orient("left").tickFormat(function(d) { return d + "%"; }).ticks(10);

To create the vertical line, I try this:

 var linev = d3.svg.line()
    .x(function(d, i) { 
      return x(data[2].Month); })
.y(function(d, i) { return y(i); }); 

 svgx.append("path")
      .datum(data)
    .style("fill", "none")
     .style("stroke", "black")
    .style("stroke-width", "1px")
      .attr("d", linev);
}

The line forms, but I cannot get it to extend in the same range from 0 to 100 percent that the axis does, as I fail to get this line right:

.y(function(d, i) { return y(i); });

How do I make that set of y values cover the y value of all all the points on the chart corresponding to the percentages from 0 to 100?

like image 313
gorilla5 Avatar asked Feb 12 '23 00:02

gorilla5


1 Answers

You can do this by appending a separate line that has the appropriate y coordinates:

svg.append("line")
   .attr("y1", y(0))
   .attr("y2", y(100))
   .attr("x1", ...)
   .attr("x2", ...)

where the coordinates for x1 and x2 are the same and determine the position of the vertical line.

like image 148
Lars Kotthoff Avatar answered Feb 13 '23 14:02

Lars Kotthoff