无法在D3中显示分位数比例的图例 [英] Unable to display legend for a quantile scale in D3
问题描述
我正在尝试显示我创建的热图的图例,但无法做到这一点.这是我的HTML
I am trying to display a legend for a heat map I have created, but am unable to do that. Here is my HTML
<html>
<head>
<title>Heat Map Data Visualization</title>
</head>
<body>
<div class='chart-area'>
<svg class='chart'></svg>
<svg class='legend'></svg>
</div>
</body>
</html>
这是我要创建的图例的代码
Here is the code for the legend I am trying to create
var legend = d3.select('.legend')
.data([0].concat(colorScale.quantiles()), function(d){
return d;
});
legend.enter()
.append('g')
.attr('class', 'legend-element');
legend.append("rect")
.attr("x", function(d, i) {
console.log(i);
return legendElementWidth * i + (width - legendElementWidth * buckets);
})
.attr("y", height)
.attr("width", legendElementWidth)
.attr("height", gridHeight / 2)
.style("fill", function(d, i) {
return colors[i];
});
当我使用Chrome开发人员工具检查该元素时,看到已创建了必需的g元素,但它们的尺寸均为0x0.
When I use Chrome Developer Tools to inspect the element, I see that the required g elements have been created but they all have dimensions of 0x0.
我在某处读到rect元素只能追加到svg元素,这就是为什么我更改HTML代码以包括带有图例类的svg元素的原因,但是我仍然没有得到任何结果.
I read somewhere that rect elements can only be appended to an svg element, which is why I changed my HTML code to include an svg element with a class of legend, however I am still not getting any result.
这里是该程序的代码笔的链接
Here is a link to the codepen for this program
http://codepen.io/redixhumayun/pen/eBqamb?editors=0010
推荐答案
我修改了您的笔,例如此:
I have modified your pen like this:
// Save the legend svg in a variable
// also changed the translate in order to keep the legend within the svg
// and place it on the right side just for the example's sake
var legendSvg = svg.append('g')
.attr('class', 'legend')
.attr("transform","translate("+ (width - 40) + ",20)")
// Define the legend as you did
var legend = d3.legendColor()
.useClass(true)
.shape('rect')
.orient('vertical')
.title('Temperature Variance')
.shapeWidth(legendElementWidth)
.scale(colorScale);
// And then call legend on the legendSvg not on svg itself
legendSvg.call(legend);
希望这会有所帮助,祝您好运!
Hope this helps, good luck!
这篇关于无法在D3中显示分位数比例的图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!