簡體   English   中英

d3.json未執行

[英]d3.json is not executed

我正在制作應該是一個非常簡單的餅圖,但是某種程度上根本沒有執行d3.json函數。 我的代碼如下:

function omst1() {
"use strict";
var chartWidth = $("#chart").width()*0.5;
var chartHeight = $("#chart").height()*0.5;

var margin = {
    top: chartWidth*0.01,
    right: chartWidth*0.01,
    bottom: chartWidth*0.01,
    left: chartWidth*0.01
},
width = chartWidth - margin.left - margin.right,
height = chartHeight - margin.top - margin.bottom,
radius = Math.min(width, height) / 2;

var color = d3.scale.ordinal()
.range(["#F1BD98", "#DA6A26", "#82A0D3", "#094D86"])

var arc = d3.svg.arc()
.outerRadius(radius - margin.bottom)
.innerRadius(radius - margin.bottom);

var pie = d3.layout.pie()
.sort(null)
.value(function(d) {
    return d.Aantal
}
);

var svg = d3.select("#omst1").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

d3.json("omstandigheden.json", type, function(error, data) {
  if (error) throw error;
  console.log(data);
  var g = svg.selectAll(".arc")
      .data(pie(data))
    .enter().append("g")
      .attr("class", "arc");

  g.append("path")
      .attr("d", arc)
      .style("fill", function(d) { return color(d.data.Omstandigheid); });

  g.append("text")
      .attr("transform", function(d) { return "translate(" + labelArc.centroid(d) + ")"; })
      .attr("dy", ".35em")
      .text(function(d) { return d.data.Omstandigheid; });
});

  function type(d) {
  d.Aantal = +d.Aantal;
  return d;
  }
}

通過此設置,console.log(data)應該返回一個對象,其對象值為omstandigheidaantal ,JSON文件是對象數組,如下所示:

  {
    "Omstandigheid": "A",
    "Aantal": 2
  },

剛開始我發現縮進不正確,或者也許我只是在錯誤的位置閉合了括號。 可悲的是我還沒有在代碼中找到錯誤,我在做什么錯?

編輯:傑拉爾多的答案后,我已經刪除了'type'參數,並更改了嘗試使用forEach而不是'type'的代碼。 現在,更改后的代碼如下:

d3.json("omstandigheden.json", function(error, data) {
      if (error) throw error;
      console.log(data);
      var g = svg.selectAll(".arc")
        .data(pie(data))
        .enter().append("g")
        .attr("class", "arc");

      g.append("path")
        .attr("d", arc)
        .style("fill", function(d) { return color(d.data.Omstandigheid); });

      g.append("text")
        .attr("transform", function(d) { return "translate(" + labelArc.centroid(d) + ")"; })
        .attr("dy", ".35em")
        .text(function(d) { return d.data.Omstandigheid; });

    data.forEach(function(d) {
        d.Aantal = +d.Aantal;
        return d;
    })
});
}

刪除JSON函數中的type JSON函數不允許“訪問器”,只有CSV和TSV函數允許它們。

因此,刪除type ,並使用JSON函數內的forEach type函數所做的所有事情。

JSON函數的第一行必須為:

d3.json("omstandigheden.json", function(error, data) {

PS:如果您是編寫JSON的人,則不需要type函數:只需將值寫為數字,而不是字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM