我有一个条形垂直条形图,底部有文字描述每个条形的含义;但是,我需要在45-65度之间旋转这个文本,以便在我有限的空间内可读。
我遇到的问题是,使用"transform","rotate(-65)"
只是旋转who文本组的中心。我理解一个问题是不选择单个文本元素来进行轮换,但我不确定如何单独选择它们。
这是使用D3的下图的javascript:
var color = d3.scale.ordinal().range(["#004467","#005481","#00659c","#0076b7","#5480ba","#a17b8b","#cf735c","#f36925"]);
var ed1_data = [867,674,901,401,127,234,608,866,153,93,701,111,813];
var ed1_dataKey = [
"Humanities",
"Social sciences",
"Life sciences",
"Physical sciences",
"Computer sciences",
"Engineering",
"Education",
"Business management",
"Health",
"Law",
"Vocational training",
"Undeclared",
"Other"
];
var ed1_width = 800;
var ed1_height = 600;
var ed1_scale = d3.scale.linear()
.domain([0,1000])
.range([ed1_height-100,0]);
var ed1_canvas = d3.select("#ed1-graph")
.append("svg")
.attr("width",ed1_width)
.attr("height",ed1_height)
.append("g");
var ed1_bars = ed1_canvas.selectAll("rect")
.data(ed1_data)
.enter()
.append("g")
.append("rect")
.attr("width",40)
.attr("fill",function(d){return color(d);})
.attr("x",function(d,i){return 20+(i*60);})
.attr("height",function(d){return (ed1_scale(0)-ed1_scale(d));})
.attr("y",function(d){return ed1_scale(d)-10});
var ed1_numbers = ed1_canvas.selectAll(".ed1numbers")
.data(ed1_data)
.enter()
.append("text")
.attr("class","ed1numbers")
.text(function(d){return d;})
.attr("width",20)
.attr("fill","#292215")
.attr("text-anchor","middle")
.attr("font-family","Franklin Gothic")
.attr("x",function(d,i){return 40+(i*60);})
.attr("height",function(d){return (ed1_scale(0)-ed1_scale(d));})
.attr("y",function(d){return ed1_scale(d)-18})
.attr("font-size","1em");
ed1_canvas.selectAll("g")
.append("text")
.attr("font-size","1em")
.attr("fill","#292215")
.attr("y",510)
.attr("text-anchor","end")
// .attr("transform","rotate(-65)") THIS IS THE ERROR LINE THAT ISN't DOING WHAT I WANT
.attr("x",function(d,i){return 40+(i*60);})
.text(function(d,i){return ed1_dataKey[i];});
CodePen易于协助:http://codepen.io/jacob_johnson/pen/mRepoG?editors=1010
这是在最后一个代码块中,目前已被注释掉。
谢谢。任何帮助表示赞赏。
答案 0 :(得分:0)
通过将可选的x&y参数传递给旋转函数,您可以设置元素绕其旋转的点。没有这些参数,旋转点将默认为当前用户坐标系。
https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/transform#Rotate
下面的钢笔演示了如何设置每个文本元素相对于其自身的旋转。
https://codepen.io/stw/pen/vVgBmm?editors=1010
.attr("transform", function (d) {
var xRot = d3.select(this).attr("x");
var yRot = d3.select(this).attr("y");
return `rotate(-65, ${xRot}, ${yRot} )` //ES6 template literal to set x and y rotation points
})