简体   繁体   中英

Adding legends to d3.js line charts

I am using the code from https://bl.ocks.org/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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM