Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Solid and dashed line in D3 line chart

I want to build a line chart using D3 so that when the data points decrease (ie 5, 4,3,2) the line is solid and when the data points increase (ie 2,3,4,5) the line is dotted.

I found this resource on dashed lines http://www.d3noob.org/2013/01/making-dashed-line-in-d3js.html just wondering where I would include the logic based on the up and down trend.

like image 572
Ray Kanani Avatar asked Feb 03 '16 21:02

Ray Kanani


1 Answers

If you set the values (x1,y1) and (x2,y2) from source and target, i would do something like this :

    append('line')
    .attr('class',function(d){
       if(d.source.y < d.target.y){ //checks if line is sloping '+' or '-'
          return 'dashed';
       } else {
          return 'solid'
       }
    })
    .attr('x1', function(d){ return d.source.x})
    .attr('y1', function(d){ return d.source.y})
    .attr('x2', function(d){ return d.target.x})
    .attr('y2', function(d){ return d.target.y})

Then in your css you would have :

.solid{
   stroke:solid;
}

.dashed{
   stroke-dasharray: 5,5; 
}

So this would be dashed if the value goes 5 then 4, but solid if it goes 4 then 5 or even 4 then 4.

like image 99
thatOneGuy Avatar answered Oct 24 '22 20:10

thatOneGuy