【发布时间】:2017-11-30 05:16:59
【问题描述】:
我正在尝试在 D3.js 中创建水平图例。我使用组元素 (g) 作为所有图例的容器,并且各个图例 (文本) 也都包含在 "g" 元素中。结果是各个图例堆叠在一起,而不是隔开。
我尝试更改图例上的 x 属性并转换/翻译。虽然 DOM 显示应用了 x 值,但图例不会移动。因此,如果 DOM 显示 legend / g 元素位于 x = 200,它仍位于 0。
我花了两天时间试图解决这个问题,并且可能查看了 50 多个示例,包括我在 StackExchange 上可以找到的任何内容。
下面的代码是我最近的尝试。它不会出现任何错误,并且 x 值会反映在 DOM 中,但元素不会移动。
我已经包含了涵盖相关位的代码(但不是所有代码)。
此处添加图例容器:
/*<note>Add container to hold legends. */
var LegendCanvas = d3.select("svg")
.append("g")
.attr("class", "legend canvas")
.attr("x", 0)
.attr("y", 0)
.attr("width", Width)
.style("fill", "#ffcccc")
.attr("transform", "translate(0,15)");
然后有一个通过 json 对象数组的循环:
var PrevElemLength = 0;
/*<note>Loop through each data series, call the Valueline variable and plot the line. */
Data.forEach(function(Key, i) {
/*<note>Add the metric line(s). */
Svg.append("path")
.attr("class", "line")
.attr("data-legend",function() { return Key.OriginId })
/*<note>Iterates through the data series objects and applies a different color to each line. */
.style("stroke", function () {
return Key.color = Color(Key.UniqueName); })
.attr("d", Valueline(Key.DataValues));
/*<note>Add a g element to the legend container. */
var Legend = LegendCanvas.append("g")
.attr("class", "legend container")
.attr("transform", function (d, i) {
if (i === 0) {
return "translate(0,0)"
} else {
PrevElemLength += this.previousElementSibling.getBBox().width;
return "translate(" + (PrevElemLength) + ",0)"
}
});
/*<note>Adds a rectangle to pre-fix each legend. */
Legend.append("rect")
.attr("width", 5)
.attr("height", 5)
.style("fill", function () {
return Key.color = Color(Key.UniqueName); });
/*<note>Adds the legend text. */
Legend.append("text")
.attr("x", function() {
return this.parentNode.getBBox().width + 5;
})
/*.attr("y", NetHeight + (Margin.bottom/2)+ 10) */
.attr("class", "legend text")
.style("fill", function () {
return Key.color = Color(Key.UniqueName); })
.text(Key.UniqueName);
以下是输出的屏幕截图: enter image description here 任何有关如何创建水平图例(不重叠图例)的帮助将不胜感激。克里斯
【问题讨论】:
标签: d3.js visualization legend