【问题标题】:D3 the x axis positions in wrong wayD3 x轴位置错误
【发布时间】:2014-03-02 21:00:20
【问题描述】:

我在显示图表 X 轴时遇到了问题,它被平移到了错误的位置。这是我的例子http://jsfiddle.net/staar2/Vww3h/1/

从 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);

【问题讨论】:

  • 您将 x 比例的域设置为 [0,1],但看起来您希望它是 [0,data.length-1]

标签: javascript d3.js bar-chart


【解决方案1】:

您需要相应地更改您的xScale 域和范围,因为

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

当您调用xScale(i) 时,据我所知,其中i 是数据元素的索引,因此域应该在0 - data.length 之间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 2021-04-07
    • 2013-08-20
    • 2016-12-27
    相关资源
    最近更新 更多