在D3中添加图表图例 [英] Adding a chart legend in D3

查看:885
本文介绍了在D3中添加图表图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将图表图例添加到我的d3js图表时遇到问题。这是我目前的方法:

I am having trouble adding a chart legend to my d3js chart. Here is my current approach:

var legend = svg.append("g")
  .attr("class", "legend")
  .attr("x", w - 65)
  .attr("y", 25)
  .attr("height", 100)
  .attr("width", 100);

legend.append("rect")
  .attr("x", w - 65)
  .attr("y", 25)
  .attr("width", 10)
  .attr("height", 10)
  .style("fill", function(d) { return color_hash[dataset.indexOf(d)][1] });

legend.append("text")
  .attr("x", w - 65)
  .attr("y", 25)
  .text(function(d) { return color_hash[dataset.indexOf(d)][0] + ": " + d; });

然后我试图设计 .legend class:

Then I am attempting to style the .legend class:

.legend {
            padding: 5px;
            font: 10px sans-serif;
            background: yellow;
            box-shadow: 2px 2px 1px #888;
        }

但我没有太多运气。

有没有人熟悉在图表中添加图例,以提供最好的方法?我在这里找不到很多资源。

Is anyone familiar with adding legends to charts able to provide the best way to do so? I am not finding many resources for this online.

这是我的整个图表:
http://jsbin.com/ewiwag/2/edit

推荐答案

您需要

目前,在尝试对矩形进行样式时会出现错误:

Currently you get an error when trying to style rectangles:

Uncaught TypeError: Cannot read property '1' of undefined 

原因:没有绑定数据

legend.append("rect")
      /*...*/
      .style("fill", function(d) { 
         // d <---- is undefined
         return color_hash[dataset.indexOf(d)][1] 
      });

请注意,D3专注于数据转换并对选择进行操作。因此,首先选择一组节点,然后绑定数据

Notice that D3 focuses on data transformation and operates on selections. So, first select a set of nodes and then bind data

legend.selectAll('rect')
      .data(dataset)
      .enter()

输入输入,可以动态添加节点和应用属性。请注意,为了避免在其他对象的顶部创建矩形,设置 y 属性会传递 i 一个整数。

Once you enter the selection with enter, you can add nodes and apply properties dynamically. Notice that to avoid creating rectangles on top of others, when setting the y property pass the i counter and multiply it by an integer.

  /*.....*/
      .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 = color_hash[dataset.indexOf(d)][1];
         return color;
      });

这是固定的例子: http://jsbin.com/ubafur/3

这篇关于在D3中添加图表图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆