2013-08-19 243 views
2

在我的d3.js條形圖中,我希望X軸標籤處於「垂直」狀態。我在「橫向」獲取標籤,但問題是一些標籤被合併。在d3.js中設置X軸標籤

<!DOCTYPE html> 
<style> 
body { 
font: 10px sans-serif; 
} 
.axis path, 
.axis line { 
fill: none; 
stroke: #000; 
shape-rendering: crispEdges; 
} 

.bar { 
fill: red; 
} 

.x.axis path { 
display: none; 
} 

</style> 
<body> 
<script src="http://d3js.org/d3.v3.min.js"></script> 
<script> 

var margin = {top: 20, right: 20, bottom: 30, left: 40}, 
width = 960 - margin.left - margin.right, 
height = 500 - margin.top - margin.bottom; 

var x = d3.scale.ordinal() 
.rangeRoundBands([0, width], .1); 

var y = d3.scale.linear() 
.range([height, 0]); 

var xAxis = d3.svg.axis() 
.scale(x) 
.orient("bottom"); 

var yAxis = d3.svg.axis() 
.scale(y) 
.orient("left"); 

var svg = d3.select("body").append("svg") 
.attr("width", width + margin.left + margin.right) 
.attr("height", height + margin.top + margin.bottom) 
.append("g") 
.attr("transform", "translate(" + margin.left + "," + margin.top + ")"); 

d3.csv("ClassRoom.csv",type,function(error,data){ 
x.domain(data.map(function(d) { return d.Name; })); 

y.domain([0, d3.max(data, function(d) { return d.Marks; })]); 

svg.append("g") 
.attr("class", "x axis") 
.attr("transform", "translate(0," + height + ")") 
.call(xAxis); 

svg.append("g") 
.attr("class", "y axis") 
.call(yAxis) 
.append("text") 
.attr("transform", "rotate(-90)") 
.attr("y", 6) 
.attr("dy", ".71em") 
.style("text-anchor", "end") 
.text("Marks"); 

svg.selectAll(".bar") 
.data(data) 
.enter().append("rect") 
.attr("class", "bar") 
.attr("x", function(d) { return x(d.Name); }) 
.attr("width", x.rangeBand()) 
.attr("y", function(d) { return y(d.Marks); }) 
.attr("height", function(d) { return height - y(d.Marks)}); 
}); 

function type(d) { 
d.Marks = +d.Marks; 
return d; 
} 

</script> 

我的CSV文件

Name,Marks 
Sathesh,15 
Somnath,45 
Naresh,35 
Venkat,25 
Prabha,78 
Dinesh,36 
+0

當你說你想要X軸標籤_垂直_你的意思是有_text-orientation_垂直,對吧? – Joum

+0

是的,你的答案是正確的 –

回答

5

你將不得不這樣做,與SVG-文本標籤。假設你以這種方式創建X軸:

 var xAxis = svg.append("g") 
      .attr({ 
       "class": "x axis", 
       transform: "translate(0," + h + ")" 
      }) 
      .call(xAxis); 

選擇文本,並應用轉型:

  xAxis.selectAll("text") 
      .attr({ 
       transform: function (d) { 
        return "rotate(-60, 0, 0)"; 
       } 
      }); 

你將不得不調整0,0的旋轉變換,以適應您的需求。另外我建議查看文本錨定屬性。但是這應該讓你開始!