D3 x轴标签
问题描述:
我试图转动我的x轴的标签我在D3中创建一个D3堆叠柱状图。所有的标签都显示为一个长串或全部在另一个之上。D3 x轴标签
这里是我的标签代码:
var shortNames = ["label1", "label2", "label3", "label4"];
// Add a label per experiment.
var label = svg.selectAll("text")
.data(shortNames)
.enter().append("svg:text")
.attr("x", function(d) { return x(d)+x.rangeBand()/2; })
.attr("y", 6)
.attr("text-anchor", "middle")
.attr("dy", ".71em")
.text(function(d) {return d})
.attr("transform", function(d) { // transform all the text elements
return "rotate(-65)" // rotate them to give a nice slope
});
我与翻译功能发挥各地和所有的标签都还在视为一个很长的字符串。我如何将翻译应用于每个单独的标签?
我可以用利润后玩耍,但现在我想有过我的标签控制。
答
我认为这个问题是转换的顺序:当你旋转文本,你还旋转了坐标系。所以,当你设置它的x位置 - 即使你设置的位置早于旋转变换 - 你实际上是沿着由旋转产生的65度轴移动它。
如果我对此正确的,那么检查标签就会发现,他们仍然由多个文本元素(每个标签都有一个),而不是所有标签一个文本元素。
通常,当您像rotate
一样引入transform
属性时,应该通过此属性执行所有转换。因此,您需要使用translate
而不是使用"x"
属性。然后它看起来像这样:
var label = svg.selectAll("text")
.data(shortNames)
.enter().append("svg:text")
// REOVE THIS: .attr("x", function(d) { return x(d)+x.rangeBand()/2; })
// AND THIS TOO: .attr("y", 6)
.attr("text-anchor", "middle")
.attr("dy", ".71em")
.text(function(d) {return d})
.attr("transform", function(d) { // transform all the text elements
return "translate(" + // First translate
x(d)+x.rangeBand()/2 + ",6) " + // Translation params same as your existing x & y
"rotate(-65)" // THEN rotate them to give a nice slope
});
+0
@sutee,这是如何为你工作的? – meetamit 2013-03-26 00:04:50
你试过'.data([shortName])'吗? – 2013-03-14 20:41:42