繁体   English   中英

d3js为条形图创建图例

[英]d3js Create legend for bar chart

我的条形图有几个问题。 目前的问题是试图创建一个传奇。 图例应为全局本地 (蓝色和绿色)。 目前这个图例生成了5个盒子 - 其中2个是彩色的。 我假设它正在通过我的数据集并为每组列生成框。 我不想要这个。

在我获得格式化的图例之后,我希望能够使它具有交互性。 因此,如果他们只想查看全局 ,那么他们会取消选择本地 ,并且图表会动态更新。 我知道我需要调整它并创建一个更新数据,域等功能。

但在开始这条道路之前,我希望能够正确地填充传奇。 但如果传说解决方案能够引领这条道路,我将不胜感激。

我有一个可以玩的小提琴

数据源

var colors =    {0: ["Local", "#377EB8"],
             1: ["Global", "#4DAF4A"]};

var dataset = [
            {"keyword": "payday loans", "global": 1400000, "local": 673000, "cpc": "14.11"},
            {"keyword": "title loans", "global": 165000, "local": 160000, "cpc": "12.53" },
            {"keyword": "personal loans", "global": 550000, "local": 301000, "cpc": "6.14"},
            {"keyword": "online personal loans", "global": 15400, "local": 12900, "cpc": "5.84"},
            {"keyword": "online title loans", "global": 111600, "local": 11500, "cpc": "11.74"}
        ];

标签代码

var legend = svg.append("g")
    .attr("class", "legend")
    //.attr("x", w - 65)
    //.attr("y", 50)
    .attr("height", 100)
    .attr("width", 100)
    .attr('transform', 'translate(-20,50)');


legend.selectAll('rect')
    .data(dataset)
    .enter()
    .append("rect")
    .attr("x", w - 65)
    .attr("y", function(d, i) {
        return i * 20;
    })
    .attr("width", 10)
    .attr("height", 10)
    .style("fill", function(d) {
        var color = colors[dataset.indexOf(d)][1];
        return color;
    });

legend.selectAll('text')
    .data(dataset)
    .enter()
    .append("text")
    .attr("x", w - 52)
    .attr("y", function(d, i) {
        return i * 20 + 9;
    })
    .text(function(d) {
        var text = colors[dataset.indexOf(d)][0];
        return text;
    });

我知道我的Colors数组/对象可能不是最有效的方法。 所以我愿意调整它,如果它有助于解决方案。 另外,我更喜欢它是水平列表而不是垂直列表。

您需要使用colors而不是dataset作为图例的.data()的参数。 为了使其工作, colors必须是一个数组而不是一个对象:

var colors = [ ["Local", "#377EB8"],
               ["Global", "#4DAF4A"] ];

然后,用于创建图例的代码变为:

var legendRect = legend.selectAll('rect').data(colors);

legendRect.enter()
    .append("rect")
    .attr("x", w - 65)
    .attr("width", 10)
    .attr("height", 10);

legendRect
    .attr("y", function(d, i) {
        return i * 20;
    })
    .style("fill", function(d) {
        return d[1];
    });

var legendText = legend.selectAll('text').data(colors);

legendText.enter()
    .append("text")
    .attr("x", w - 52);

legendText
    .attr("y", function(d, i) {
        return i * 20 + 9;
    })
    .text(function(d) {
        return d[0];
    });

如果更新的小提琴

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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