添加新数据时,D3.JS条形图列偏移

时间:2016-05-13 05:27:08

标签: javascript html d3.js javascript-objects

我目前正在与D3.JS合作,尝试每24小时添加一张现有图表。使用这样的JSON数据:

[{"name": "bill", "val": 28}, {"name": "kevin", "val": 46}, {"name": "ryan", "val": 23},{"name": "ville", "val": 56}]

我的Y轴上有一个频率值,我的x轴上有一个用户名。我认为我的贴装功能是正确的,但是当添加新列时(尽管偏移量应保持不变),所有列都会移位。目标是能够添加列(新数据)并将列(rects)保留在正确的用户名之上。

这是我目前的工作代码:

    <html>
<head>
  <script type="text/javascript" src="d3.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
  <script type="data/json" src="data.json"></script> 

<style>
#chart rect{
  fill: #4aaeea;
}
#chart text{
  fill: white;
  font: 10px sans-serif;
  text-anchor: end; 
}
.axis text{
  font: 10px sans-serif;
}
.axis path, .axis line{
  fill: none;
  stroke : #fff;
  shape-rendering: crispEdges;
}
body{
  background: #1a1a1a;
  color : #eaeaea;
  padding : 5px;
}
  </style>
  </head>
<body>
    <div id="chart"</div>
<script>
var margin ={top:20, right:30, bottom:30, left:40},
    width=960-margin.left - margin.right, 
    height=500-margin.top-margin.bottom;
// scale to ordinal because x axis is not numerical
var x = d3.scale.ordinal().rangeRoundBands([0, width], .1);
//scale to numerical value by height
var y = d3.scale.linear().range([height, 0]);
var chart = d3.select("#chart")  
              .append("svg")  //append svg element inside #chart
              .attr("width", width+(2*margin.left)+margin.right)    //set width
              .attr("height", height+margin.top+margin.bottom);  //set height
var xAxis = d3.svg.axis()
              .scale(x)
              .orient("bottom");  //orient bottom because x-axis will appear below the bars
var yAxis = d3.svg.axis()
              .scale(y)
              .orient("left");
var data;
d3.json("http://localhost:8000/data.json", function(error, data){
  if (error) return console.warn(error);
  x.domain(data.map(function(d){ return d.name}));
  y.domain([0, d3.max(data, function(d){return d.val})]);

  var bar = chart.selectAll("g")
                    .data(data)
                  .enter()
                    .append("g")
                    .attr("transform", function(d, i){
                      return "translate("+x(d.name)+", 0)";
                    });
 console.log(margin.left); 
  bar.append("rect")
      .attr("y", function(d) { 
        return y(d.val); 
      })
      .attr("x", function(d,i){
        return x(margin.left + 2);
      })
      .attr("height", function(d) { 
        return height - y(d.val); 
      })
      .attr("width", Math.min.apply(null, [x.rangeBand()-2, 100]));
      //.attr("width", x.rangeBand());  //set width base on range on ordinal data
  bar.append("text")
      .attr("x", (margin.left * 2.2))
      .attr("y", function(d) { return y(d.val) })
      .attr("dy", ".75em")
      .text(function(d) { return d.val; });

  chart.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate("+margin.left+","+ height+")")        
        .call(xAxis);

  chart.append("g")
        .attr("class", "y axis")
        .attr("transform", "translate("+margin.left+",0)")
        .call(yAxis)
        .append("text")
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", ".71em")
        .style("text-anchor", "end")
        .text("Frequency");
});
function type(d) {
    d.name = +d.name; // coerce to number
    return d;
  }
</script>

1 个答案:

答案 0 :(得分:1)

我对g元素的位置属性进行了一些调整,其中包含条形rect元素以及文本元素的dxdy属性。

希望这个有效的代码片段有所帮助。

var margin = {
    top: 20,
    right: 30,
    bottom: 30,
    left: 40
  },
  width = 960 - margin.left - margin.right,
  height = 500 - margin.top - margin.bottom;
// scale to ordinal because x axis is not numerical
var x = d3.scale.ordinal().rangeRoundBands([0, width], .1);

//scale to numerical value by height
var y = d3.scale.linear().range([height, 0]);

var chart = d3.select("#chart")
  .append("svg") //append svg element inside #chart
  .attr("width", width + margin.left + margin.right) //set width
  .attr("height", height + margin.top + margin.bottom); //set height

var xAxis = d3.svg.axis()
  .scale(x)
  .orient("bottom"); //orient bottom because x-axis will appear below the bars

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

var data = [{
  "name": "bill",
  "val": 28
}, {
  "name": "kevin",
  "val": 46
}, {
  "name": "ryan",
  "val": 23
}, {
  "name": "ville",
  "val": 56
}];

x.domain(data.map(function(d) {
  return d.name
}));
y.domain([0, d3.max(data, function(d) {
  return d.val
})]);

var barWidth = Math.min.apply(null, [x.rangeBand() - 2, 100]);

var bar = chart.selectAll("g")
  .data(data)
  .enter()
  .append("g")
  .attr("transform", function(d, i) {
    return "translate(" + x(d.name) + ", " + y(d.val) + ")";
  });

bar.append("rect")
  .attr("y", 0)
  .attr("x", barWidth - 10)
  .attr("height", function(d) {
    return height - y(d.val);
  })
  .attr("width", barWidth);

bar.append("text")
  .attr("x", barWidth - 10)
  .attr("y", 0)
  .attr("dx", barWidth / 2)
  .attr("dy", ".75em")
  .text(function(d) {
    return d.val;
  });

chart.append("g")
  .attr("class", "x axis")
  .attr("transform", "translate(" + margin.left + "," + height + ")")
  .call(xAxis);

chart.append("g")
  .attr("class", "y axis")
  .attr("transform", "translate(" + margin.left + ",0)")
  .call(yAxis)
  .append("text")
  .attr("transform", "rotate(-90)")
  .attr("y", 6)
  .attr("dy", ".71em")
  .style("text-anchor", "end")
  .text("Frequency");

function type(d) {
  d.name = +d.name; // coerce to number
  return d;
}
#chart rect {
  fill: #4aaeea;
}
#chart text {
  fill: white;
  font: 10px sans-serif;
  text-anchor: end;
}
.axis text {
  font: 10px sans-serif;
}
.axis path,
.axis line {
  fill: none;
  stroke: #fff;
  shape-rendering: crispEdges;
}
body {
  background: #1a1a1a;
  color: #eaeaea;
  padding: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id="chart" </div>