如何将图例添加到图表?
问题描述:
如何将图例添加到图表(see fiddle)?我尝试按如下方式定义图例,但图表消失(请参阅this fiddle)。如何将图例添加到图表?
var height = 900, width = 900;
var gridSize = Math.floor(width/42);
var legendElementWidth = gridSize*2;
var legend = svg.selectAll(".legend")
.data([0].concat(colorScaleDomain.quantiles()), function(d) { return d; });
legend.enter().append("g")
.attr("class", "legend");
legend.append("rect")
.attr("x", height)
.attr("y", function(d, i) { return legendElementWidth * (i-0.5); })
.attr("width", gridSize/2)
.attr("height", legendElementWidth)
.style("fill", function(d, i) { return colors[i]; });
legend.append("text")
.attr("class", "mono")
.text(function(d) { return "≥ " + Math.round(d) + "%"; })
.attr("x", (height) + gridSize)
.attr("y", function(d, i) { return legendElementWidth*i; });
legend.exit().remove();
答
这是问题的列表:
没有
colorScaleDomain.quantiles()
。应改为colorScale.quantiles()
。-
在没有z索引的SVG中,元素的顺序非常重要。所以,你的传说......
legend.enter().append("g") .attr("class", "legend");
...应该来图表的绘制代码之后。但是,步骤,甚至可以忽略不计,这是因为第三个问题的:
-
你的图例是外的SVG。我纠正与:
var svg = d3.select("body").append("svg") .attr("width", diameter + 200)//adding some space in the SVG
而且一些幻数的传说代码。相应地改变它们(在大多数情况下,幻数不是一个好习惯)。
这里是您更新的小提琴:https://jsfiddle.net/hsq05oq9/
谢谢。如果我需要在图例中显示绝对数字,该怎么办?此外,'colorScale'已被定义为分位数:'ar colorScale = d3.scale.quantile() .domain(colorScaleDomain) .range(colors);'。我稍微误解了为什么需要在'.data([0] .concat(colorScale.quantiles()),function(d){return d;});''中重新运行'colorScale.quantiles() – Dinosaurius
'分位数()'是规模。 'quantiles()'返回分位数。他们不同。 –
哦,我不知道这个。抱歉。无论如何,如果你能指出如何在图例中获得绝对数字,我非常感激。 – Dinosaurius