使用d3.js将csv文件中的数据显示到BarGraph中

时间:2018-05-08 17:57:39

标签: javascript d3.js

您好我正在尝试使用javascript将csv文件中的数据显示到BarGraph中。表示属性y:预期长度," NaN"。在javascript中。我到目前为止尝试的代码是:

var margin = {top: 20, right: 10, bottom: 100, left:50},
 width = 700 - margin.right - margin.left,
height = 500 - margin.top - margin.bottom;
var svg = d3.select("body")
.append("svg")
  .attr ({
    "width": width + margin.right + margin.left,
    "height": height + margin.top + margin.bottom
  })
.append("g")
  .attr("transform","translate(" + margin.left + "," + margin.right + ")");
var xScale = d3.scale.ordinal()
.rangeRoundBands([0,width], 0.2, 0.2);

var yScale = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(yScale)
.orient("left");

d3.csv("aa.csv", function(error,data) {
if(error) console.log("Error: can not be loaded!");
 data.forEach(function(d) {
d.c= d.c;
d.a= +d.a;      
console.log(d.a); 
});
  data.sort(function(a,b) {
return b.a- a.a;
 });
  xScale.domain(data.map(function(d) { return d.c; }) );
yScale.domain([0, d3.max(data, function(d) { return d.a; } ) ]);
  svg.selectAll('rect')
.data(data)
.enter().append('rect')
.append('rect')
.attr("height", 0)
.attr("y", height)
.transition().duration(3000)
.delay( function(d,i) { return i * 200; })
.attr({
 "x": function(d) { return xScale(d.c); },
  "y": function(d) { return yScale(d.a); },
  "width": xScale.rangeBand(),
  "height": function(d) { return  height - yScale(d.a); }
})

.style("fill", function(d,i) { return 'rgb(20, 20, ' + ((i * 30) + 100) + ')'});

svg.selectAll('text')
        .data(data)
        .enter()
        .append('text')

.text(function(d){
return d.a;
        })
.attr({
            "x": function(d){ return xScale(d.c) +  xScale.rangeBand()/2; },
            "y": function(d){ return yScale(d.a)+ 12; },
            "font-family": 'sans-serif',
            "font-size": '13px',
            "font-weight": 'bold',
            "fill": 'white',
            "text-anchor": 'middle'
});

    svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis)
    .selectAll("text")
    .attr("dx", "-.8em")
    .attr("dy", ".25em")
    .attr("transform", "rotate(-60)" )
    .style("text-anchor", "end")
    .attr("font-size", "10px");

    svg.append("g")
    .attr("class", "y axis")
    .call(yAxis)
    .append("text")
    .attr("transform", "rotate(-90)")
    .attr("x", -height/2)
    .attr("dy", "-3em")
    .style("text-anchor", "middle")
    .text("Trillions of US Dollars ($)");
});

以下是index.html文件代码

<!DOCTYPE html>
<html>
  <head>
<meta charset="utf-8">
<title>Show data in BaraGraph</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js" 
charset="utf-8"></script>
</head>
<body>
<h1 style="text-align:center;">Show Maths data in BaraGraph</h1>
<script type="text/javascript" src="showData.js"></script>
</body>
</html>

请有人帮我解决这个问题,因为我花了太多时间没有找到合适的解决方案

我使用过的数据是:

c                     a
-----                 ------
John                  9.4
Smith                 3.5
Mark                  3.3
Alan                  8.9

1 个答案:

答案 0 :(得分:2)

运行代码时,我没有收到任何错误消息。

您的代码也有错误。您要将'rect'元素追加两次(请参阅下面的代码段):

svg.selectAll('rect')
                .data(data)
                .enter().append('rect')
                .append('rect') // 'rect' element appended twice

这是一个更新且有效的代码:

var margin = {
    top: 20,
    right: 10,
    bottom: 100,
    left: 50
  },
  width = 700 - margin.right - margin.left,
  height = 500 - margin.top - margin.bottom;
var svg = d3.select("body")
  .append("svg")
  .attr({
    "width": width + margin.right + margin.left,
    "height": height + margin.top + margin.bottom
  })
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.right + ")");
var xScale = d3.scale.ordinal()
  .rangeRoundBands([0, width], 0.2, 0.2);

var yScale = d3.scale.linear()
  .range([height, 0]);
var xAxis = d3.svg.axis()
  .scale(xScale)
  .orient("bottom");
var yAxis = d3.svg.axis()
  .scale(yScale)
  .orient("left");

d3.csv("mathResults.csv", function(error, data) {
  if (error) console.log("Error: can not be loaded!");
  data.forEach(function(d) {
    d.Name = d.Name;
    d.Grade = +d.Grade;
    console.log(d.Grade);
  });
  data.sort(function(a, b) {
    return b.Grade - a.Grade;
  });
  xScale.domain(data.map(function(d) {
    return d.Name;
  }));
  yScale.domain([0, d3.max(data, function(d) {
    return d.Grade;
  })]);
  svg.selectAll('rect')
    .data(data)
    .enter()
    .append('rect')
    .attr("height", 0)
    .attr("y", height)
    .transition().duration(3000)
    .delay(function(d, i) {
      return i * 200;
    })
    .attr({
      "x": function(d) {
        return xScale(d.Name);
      },
      "y": function(d) {
        return yScale(d.Grade);
      },
      "width": xScale.rangeBand(),
      "height": function(d) {
        return height - yScale(d.Grade);
      }
    })
    .style("fill", function(d, i) {
      return 'rgb(20, 20, ' + ((i * 30) + 100) + ')'
    });

  svg.selectAll('text')
    .data(data)
    .enter()
    .append('text')

    .text(function(d) {
      return d.Grade;
    })
    .attr({
      "x": function(d) {
        return xScale(d.Name) + xScale.rangeBand() / 2;
      },
      "y": function(d) {
        return yScale(d.Grade) + 12;
      },
      "font-family": 'sans-serif',
      "font-size": '13px',
      "font-weight": 'bold',
      "fill": 'white',
      "text-anchor": 'middle'
    });

  svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis)
    .selectAll("text")
    .attr("dx", "-.8em")
    .attr("dy", ".25em")
    .attr("transform", "rotate(-60)")
    .style("text-anchor", "end")
    .attr("font-size", "10px");

  svg.append("g")
    .attr("class", "y axis")
    .call(yAxis)
    .append("text")
    .attr("transform", "rotate(-90)")
    .attr("x", -height / 2)
    .attr("dy", "-3em")
    .style("text-anchor", "middle")
    .text("Trillions of US Dollars ($)");
});
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Show data in BaraGraph</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js" charset="utf-8"></script>
</head>

<body>
  <h1 style="text-align:center;">Show Maths data in BaraGraph</h1>

</body>

</html>