Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a dashed line legend with d3.js

Tags:

d3.js

I usually make a line legend by appending a rect giving it a very small height so that it looks like a line.

But now I need a dashed line legend. I am not able to do it by my old way. Can anyone show me a quick example of how to make a line legend with append('path') with d3.js?

Dashed line legend example

like image 646
User2403 Avatar asked Feb 19 '16 22:02

User2403


1 Answers

You can make it like this with a line DOM:

  var legend = svg.selectAll(".legend")
      .data(ageNames.slice().reverse())//data set for legends
    .enter().append("g")
      .attr("class", "legend")
      .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });

  legend.append("line")//making a line for legend
      .attr("x1", width - 28)
      .attr("x2", width)
      .attr("y1", 10)
      .attr("y2", 10)
      .style("stroke-dasharray","5,5")//dashed array for line
      .style("stroke", color);

  legend.append("text")
      .attr("x", width - 44)
      .attr("y", 9)
      .attr("dy", ".35em")
      .style("text-anchor", "end")
      .text(function(d) { return d; });

Working example here

Hope this work

like image 132
Cyril Cherian Avatar answered Sep 16 '22 12:09

Cyril Cherian