admin管理员组

文章数量:1312888

I am using the code from to draw a multi-series line chart.

The lines have labels at the ends, but it gets a little mess up if the lines are close to each other.

Is it possible to add legends to line charts with d3? I have looked through the API, but I can't seem to find anything.

I am using the code from https://bl.ocks/mbostock/3884955 to draw a multi-series line chart.

The lines have labels at the ends, but it gets a little mess up if the lines are close to each other.

Is it possible to add legends to line charts with d3? I have looked through the API, but I can't seem to find anything.

Share Improve this question asked Aug 15, 2016 at 11:35 JamgreenJamgreen 11.1k32 gold badges122 silver badges231 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

There is no function for automatically creating legends in the default D3. D3 is a low level data visualization library with very high flexibility in terms of the final results. However, a legend is nothing but some shapes and texts so you sure can create it using D3. Here is something to get you started.

var legend_keys = ["Austin", "New York", "San Francisco"]

var lineLegend = svg.selectAll(".lineLegend").data(legend_keys)
    .enter().append("g")
    .attr("class","lineLegend")
    .attr("transform", function (d,i) {
            return "translate(" + width + "," + (i*20)+")";
        });

lineLegend.append("text").text(function (d) {return d;})
    .attr("transform", "translate(15,9)"); //align texts with boxes

lineLegend.append("rect")
    .attr("fill", function (d, i) {return color_scale(d); })
    .attr("width", 10).attr("height", 10);

本文标签: javascriptAdding legends to d3js line chartsStack Overflow