繁体   English   中英

使用 d3js v7 错误读取条形图:<rect> 属性高度:预期长度,“NaN”

[英]Prob reading bar chart with d3js v7 Error: <rect> attribute height: Expected length, "NaN"

亲爱的堆栈溢出社区,

我一直在尝试使用 d3v7 为我的一个 Uni 项目创建一个条形图,遵循_Blocks_示例。 但是,我收到了这个问题标题中提到的错误。 显然,我的代码在读取我的数据时出现问题,但我不知道如何解决这个问题。 如果您能在这里帮助我,那将非常有帮助:)

这是我的代码:

var margin = {top: 5, right:10, bottom:5, left:10},
    width = 575 - margin.left - margin.right,
    height = 200 - margin.top - margin.bottom;

// set the ranges
var x = d3.scaleBand()
          .range([0, width])
          .padding(0.1);
var y = d3.scaleLinear()
          .range([height, 0]);
          
// append the svg object to the body of the page
// append a 'group' element to 'svg'
// moves the 'group' element to the top left margin
var svg = d3.select("#bar").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", 
          "translate(" + margin.left + "," + margin.top + ")");

// get the data
d3.csv("canton_pop.csv").then(function(data) {

  // format the data
  data.forEach(function(d) {
    d.Population = +d.Population;
  });

  // Scale the range of the data in the domains
  x.domain(data.map(function(d) { return d.Canton; }));
  y.domain([0, d3.max(data, function(d) { return d.Population; })]);

  // append the rectangles for the bar chart
  svg.selectAll(".bar_chart")
      .data(data)
    .enter().append("rect")
      .attr("class", "bar_chart")
      .attr("x", function(d) { return x(d.Canton); })
      .attr("width", x.bandwidth())
      .attr("y", function(d) { return y(d.Population); })
      .attr("height", function(d) { return height - y(d.Population); });

  // add the x Axis
  svg.append("g")
      .attr("transform", "translate(0," + height + ")")
      .call(d3.axisBottom(x));

  // add the y Axis
  svg.append("g")
      .call(d3.axisLeft(y));

});

这是我的 CSV 文件的样子:

Canton;Population
Zürich;1553423
Bern;1043132
Luzern;416347
Uri;36819
Schwyz;162157
Obwalden;38108
Nidwalden;43520
Glarus;40851
Zug;128794
Fribourg;325496
Solothurn;277462
Basel-Stadt;196735
Basel-Landschaft;290969
Schaffhausen;83107
Appenzell Ausserrhoden;55309
Appenzell Innerrhoden;16293
St. Gallen;514504
Graubünden;200096
Aargau;694072
Thurgau;282909
Ticino;350986
Vaud;814762
Valais;348503
Neuchâtel;175894
Genève;506343
Jura;73709

运行我的代码时,我能够可视化图形轴,但没有出现条形图,并且轴没有任何刻度(下面是我得到的结果和控制台中出现的错误的图像)。 希望有人可以在这里帮助我。

空白条形图: 空白条形图

我的控制台中出现的错误消息: 出现在我的控制台中的错误消息

好的,我刚刚意识到问题出在我的 CSV 文件中,实际上我使用的是“;” 当我需要使用“,”时作为分隔符

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM