这是一个技术/优化问题。使用 SA 和 bl.ocks 中的许多来源,我已经能够获得带旋转文本的水平图例,如此处所示。出于专有原因,我已经剪掉了它。
这是我使用的代码:
var svg_legend = d3.select("body").append("svg")
.attr("width", width+margin.left)
.attr("height", 180)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
rects=svg_legend.selectAll("rect")
.data(coldomain)
.enter().append("rect")
.attr("height", 15)
.attr("x", function(d, i) { return (i+1)*((width-margin.left)/coldomain.length); })
.attr("width", 15)
.style("fill", color);
text = svg_legend.selectAll("text")
.data(coldomain)
.enter().append("text")
.text(function(d){return d})
.style("fill", 'black')
.attr("y", 60)
.attr("x", 0)
.attr("text-anchor", "end")
.style("font-size", "12px")
.attr("transform", function(d, i) { return "translate(" + (i)*((width-margin.left)/coldomain.length)+",0) rotate(-65," + 0+"," + 0+") "; })
这样可行,但似乎我应该能够一次性完成矩形和文本,这样您就不必担心让它们对齐,b/c 文本会以某种方式与矩形动态同步。是否有更好的方法来实现上述目标?
感谢您的任何建议。
最佳答案
一种方法可能是在主组下创建组,将数据绑定(bind)到该组,翻译它们,然后将矩形和文本附加到每个组。该策略的概要是:
var svg = d3.select('body').append('svg'),
grp = svg.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
// Compute the actual translation and replace the zeros
var groups = grp.selectAll('g')
.data(coldomain)
.enter()
.append('g')
.attr('transform', function(d) { return 'translate(0, 0)'; });
// The rectangles are now relative to the parent group
groups.append('rect')
.attr('x', 0)
.attr('y', -10)
.attr('width', 10)
.attr('height', 10);
// The text position is now relative to the parent group
groups.append('text')
.attr('x', 0)
.attr('y', 10)
.text(function(d) { return d.name; });
绑定(bind)到组的数据项被传递给它们的子元素,在本例中为 rect
和 text
元素。
关于javascript - D3 : improving my shape-text linkup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17538062/