2014-03-02 133 views
0

我遇到了错误位置翻译显示图表X轴的问题。这是我的例子http://jsfiddle.net/staar2/Vww3h/1/D3 x轴位置错误

正如你可以从HTML检查器看svg元素得到翻译错误。我认为xScale设置错误。

var data = JSON.parse('[{"hour":0,"time":147},{"hour":1,"time":0},{"hour":2,"time":74},{"hour":3,"time":141},{"hour":4,"time":137},{"hour":5,"time":210},{"hour":6,"time":71},{"hour":7,"time":73},{"hour":8,"time":0},{"hour":9,"time":68},{"hour":10,"time":70},{"hour":11,"time":0},{"hour":12,"time":147},{"hour":13,"time":0},{"hour":14,"time":0},{"hour":15,"time":69},{"hour":16,"time":67},{"hour":17,"time":67},{"hour":18,"time":66},{"hour":19,"time":0},{"hour":20,"time":0},{"hour":21,"time":66},{"hour":22,"time":210},{"hour":23,"time":0}] '); 

    var w = 15, 
     h = 80; 

    var xScale = d3.scale.linear() 
     .domain([0, 1]) 
     .range([0, w]); 

    var yScale = d3.scale.linear() 
     .domain([0, d3.max(data, function (d) { 
      return d.time; 
     })]) 
     .rangeRound([5, h]); 

    var xAxis = d3.svg.axis() 
     .scale(xScale) 
     .orient("bottom") 
     .ticks(5); 

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

    var chart = d3.select("#viz") 
    .append("svg") 
    .attr("class", "chart") 
    .attr("width", w * data.length - 1) 
    .attr("height", h); 

    chart.selectAll("rect") 
    .data(data) 
    .enter().append("rect") 
    .attr("x", function(d, i) { 
     return xScale(i) - 0.5; 
    }) 
    .attr("y", function(d) { 
     return h - yScale(d.time) - 0.5; 
    }) 
    .attr("width", w) 
    .attr("height", function(d) { 
     return yScale(d.time); 
    }); 

    chart.selectAll("text") 
    .data(data) 
    .enter() 
    .append("text") 
    .text(function(d) { 
     if (d.time > 10) { 
     return Math.round(d.time); 
     } 
    }) 
    .attr("font-family", "sans-serif") 
    .attr("font-size", "11px") 
    .attr("fill", "#FFF") 
    .attr("text-anchor", "middle") 
    .attr("x", function(d, i) { 
     return xScale(i) + w/2; 
    }) 
    .attr("y", function(d) { 
     return h - yScale(d.time) - 0.5 + 10; 
    }); 

    chart.append("g") 
    .attr("transform", "translate(0," + (h) + ")") 
    .call(xAxis); 
+0

您正在将x标尺的域设置为'[0,1]',但看起来您期待它是'[0,data.length-1]'。 –

回答

0

你需要改变你的xScale域和相应范围,同时,作为

xScale .domain([0, data.length-1]) .range([0, w*(data.length-1)])

,而你打电话xScale(i)其中i是数据元素的索引,据我了解,和所以域名应该在0 - data.length之间。