2014-12-06 115 views
0

我正在使用D3的條形圖,但是當我繪製的條形圖的X蜱不槓下對齊。我想我沒有正確地改變酒吧。我使用了以下示例http://bost.ocks.org/mike/bar/,並且我已經能夠創建條形圖。任何幫助表示讚賞。先謝謝你。D3條形圖X-蜱不對齊

<!DOCTYPE html> 
<meta charset="utf-8"> 
<style> 

.bar { 
    fill: steelblue; 
} 

.bar:hover { 
    fill: brown; 
} 

.axis { 
    font: 10px sans-serif; 
} 

.axis path, 
.axis line { 
    fill: none; 
    stroke: #000; 
    shape-rendering: crispEdges; 
} 

.x.axis path { 
    display: none; 
} 

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

<script> 
     var data = [277, 407, 422, 279, 680, 485, 1624, 729, 327, 425, 205, 236]; 
     var margin = {top: 30, right: 30, bottom: 30, left: 30}, 
      width = 480 - margin.left - margin.right, 
      height = 340 - margin.top - margin.bottom; 

     var labels = [ {"key": "WS1"},{"key": "WS2"},{"key": "WS3"},{"key": "WS4"}, 
       {"key": "WS5"},{"key": "WS6"},{"key": "WS7"},{"key": "WS8"}, 
       {"key": "WS9"},{"key": "WS10"},{"key": "WS11"},{"key": "WS12"}, 
       {"key": "WS13"}]; 

     var colo = ['rgb(179,205,227)','rgb(140,150,198)','rgb(136,86,167)','rgb(129,15,124)', 
     'rgb(254,217,142)','rgb(254,153,41)','rgb(217,95,14)','rgb(153,52,4)', 
     'rgb(251,180,185)','rgb(247,104,161)','rgb(197,27,138)','rgb(122,1,119)'] 

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

     var x = d3.scale.ordinal() 
      .domain(labels.map(function(d) { return d.key})) 
      .rangeRoundBands([0, width]); 

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

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

     var barWidth = width/data.length; 
     console.log(width); 
     console.log(height); 
     console.log(data.length); 

     var bar = chart.selectAll("g") 
      .data(data) 
      .enter().append("g"); 

      var ii = 0; 
      bar.append("rect") 
      .attr("fill", function(d) { ii += 1; return colo[ii-1]; }) 
        .attr("y", function(d) { return y(d); }) 
        .attr("x", function(d,i) { return x(d.key)}) 
        .attr("width", barWidth - 1) 
        .attr("height", function(d) { return height - y(d); }) 
      .attr("transform", function(d, i) { 
         return "translate(" + ((i) * (barWidth)) + ", 0)"; 
         }); 

     chart.append("g") 
      .attr("class", "x axis") 
      .attr("transform", "translate(0," + (height) + ")") 
      .call(xAxis); 
</script> 

回答

1

labels陣列有13個項目,但你data陣列只有12使長度相等,你的每一跳都排隊。

+0

謝謝,我想出了問題。 – Pete 2014-12-06 05:38:06