最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Adding legends to d3.js line charts - Stack Overflow

programmeradmin0浏览0评论

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);
发布评论

评论列表(0)

  1. 暂无评论