2013-11-27 91 views
1

我需要设置散点图的颜色图例。 我已经设置了比例尺,并且它正在散点图上的点上工作,但是现在我想要做的是为每种颜色绘制一个小方块,并用颜色本身填充以显示图的图例。 像这样的事情在我的图形开始: enter image description hereD3.js〜放置矩形与for循环和着色它们

我试图建立功能相应地拉拢他们,但失败了,这里是我的尝试:

var colore = d3.scale.ordinal() 
    .domain(d3.extent(dataset, function (d) { return d.Peso; })) 
    .range(["#fee0d2","#fcbba1","#fc9272","#fb6a4a","#ef3b2c","#cb181d","#a50f15","#67000d"]); 

,并提请平方功能:

svg.selectAll("rect") 
    .data(colore.range()) 
    .enter() 
    .append("rect") 
    .attr("fill", function (i) { return colore(i); }) 
    .attr("x", function (i) {for (i=1; i <= colore.range().length; i++) 
     { return (i * 12) + "px"; } 
     }) 
    .attr("y", margin - 8 + "px") 
    .attr("width", 8 + "px") 
    .attr("height", 8 + "px"); 

这追加到SVG元件8米的正方形,但堆叠到海誓山盟,像这样(红色的): enter image description here

所以我不知道如何纠正我的功能,我认为这是错误发生的地方。预先感谢任何帮助!

回答

2

问题是你没有使用绑定到每个矩形的data,而是每次循环遍历所有的颜色。尝试是这样的:

svg.selectAll("rect") 
    .data(colore.range()).enter() 
    .append("rect") 
    .attr("fill", function (color){ return color; }) 
    .attr("x", function (color, index){ return (index * 12) + "px"; }) 
    .attr("y", margin - 8 + "px") 
    .attr("width", 8 + "px") 
    .attr("height", 8 + "px"); 

要注意的关键问题是,如果你可以传递一个属性的函数,它接受一个对象和索引,然后将获得应用到每个数据参数。使用这种方法,我得到这个:

example output

+0

我解决了它,正要删除它,我并不需要使用for循环,因为我已经拥有的数据阵列,现在编辑答案 – tomtomtom

+0

@tomtomtom:你总是可以回答自己的问题,以便以后如果其他人有相同的问题,他们可以看到答案。或者,如果我的解决方案也适用于你,你可以upvote /接受,以及:) – mdml

+0

好,没关系我会接受你的正确,这个编辑是有效的!谢谢 :) – tomtomtom