Javascript d3饼图不';t使用字典列表从JSON文件中提取数据

Javascript d3饼图不';t使用字典列表从JSON文件中提取数据,javascript,json,d3.js,Javascript,Json,D3.js,我有一个包含数据的.json文件,我想用它制作一个d3甜甜圈(饼图)。我对javascript不是特别精通,我能找到的每个示例要么来自内联json数据,要么json文件的结构与我的不同(我的是一个字典列表;它们通常是单个字典)。我已经排除故障几天了,但不知怎么的,我无法找到任何真正有效的方法。有什么想法/建议吗 at的示例使用内联json数据呈现带标签的圆环图。我试图通过以下方式修改该代码: 从/data/all-facet-digidated.json中提取json数据 提取每个字典的“fa

我有一个包含数据的.json文件,我想用它制作一个d3甜甜圈(饼图)。我对javascript不是特别精通,我能找到的每个示例要么来自内联json数据,要么json文件的结构与我的不同(我的是一个字典列表;它们通常是单个字典)。我已经排除故障几天了,但不知怎么的,我无法找到任何真正有效的方法。有什么想法/建议吗

at的示例使用内联json数据呈现带标签的圆环图。我试图通过以下方式修改该代码:

  • 从/data/all-facet-digidated.json中提取json数据
  • 提取每个字典的“facet”键(“true”和“false”)的标签,以及每个字典的“count”键(373977和55433)的值
  • 更改颜色比例域以匹配刻面关键点(“true”和“false”)
/data/all-facet-digidated.json看起来像:

[
  {
    "count": "55433",
    "facet": "true"
  },  
  {
    "count": "373977",
    "facet": "false"
  }
]

    <div id="chart"></div> <!-- div containing the donut chart -->


    <script src="//d3js.org/d3.v4.min.js"></script>


    <script>
    // set the dimensions and margins of the graph
    var width = 450
        height = 450
        margin = 40

    // The radius of the pieplot is half the width or half the height (smallest one) minus margin.
    var radius = Math.min(width, height) / 2 - margin

    // append the svg object to the div called 'chart'
    var svg = d3.select("#chart")
      .append("svg")
        .attr("width", width)
        .attr("height", height)
      .append("g")
        .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");


    // Parse the Data
    d3.json("/data/all-facet-digitized.json", function(data) {

      // set the color scale
      var color = d3.scaleOrdinal()
        .domain(["true","false"])
        .range(d3.schemeDark2);

      // Compute the position of each group on the pie:
      var pie = d3.pie()
        .sort(null) // Do not sort group by size
        .value(function(d) {return d.count; })
      var data_ready = pie(d3.entries(data))

      // The arc generator
      var arc = d3.arc()
        .innerRadius(radius * 0.5)         // This is the size of the donut hole
        .outerRadius(radius * 0.8)

      // Another arc that won't be drawn. Just for labels positioning
      var outerArc = d3.arc()
        .innerRadius(radius * 0.9)
        .outerRadius(radius * 0.9)

      // Build the pie chart: Basically, each part of the pie is a path that we build using the arc function.
      svg
        .selectAll('allSlices')
        .data(data_ready)
        .enter()
        .append('path')
        .attr('d', arc)
        .attr('fill', function(d){ return(color(d.facet)) })
        .attr("stroke", "white")
        .style("stroke-width", "2px")
        .style("opacity", 0.7)

      // Add the polylines between chart and labels:
      svg
        .selectAll('allPolylines')
        .data(data_ready)
        .enter()
        .append('polyline')
          .attr("stroke", "black")
          .style("fill", "none")
          .attr("stroke-width", 1)
          .attr('points', function(d) {
            var posA = arc.centroid(d) // line insertion in the slice
            var posB = outerArc.centroid(d) // line break: we use the other arc generator that has been built only for that
            var posC = outerArc.centroid(d); // Label position = almost the same as posB
            var midangle = d.startAngle + (d.endAngle - d.startAngle) / 2 // we need the angle to see if the X position will be at the extreme right or extreme left
            posC[0] = radius * 0.95 * (midangle < Math.PI ? 1 : -1); // multiply by 1 or -1 to put it on the right or on the left
            return [posA, posB, posC]
          })

      // Add the polylines between chart and labels:
      svg
        .selectAll('allLabels')
        .data(data_ready)
        .enter()
        .append('text')
          .text( function(d) { console.log(d.facet) ; return d.facet} )
          .attr('transform', function(d) {
              var pos = outerArc.centroid(d);
              var midangle = d.startAngle + (d.endAngle - d.startAngle) / 2
              pos[0] = radius * 0.99 * (midangle < Math.PI ? 1 : -1);
              return 'translate(' + pos + ')';
          })
          .style('text-anchor', function(d) {
              var midangle = d.startAngle + (d.endAngle - d.startAngle) / 2
              return (midangle < Math.PI ? 'start' : 'end')
          })
      })

    </script>

我的html文件中的代码如下所示:

[
  {
    "count": "55433",
    "facet": "true"
  },  
  {
    "count": "373977",
    "facet": "false"
  }
]

    <div id="chart"></div> <!-- div containing the donut chart -->


    <script src="//d3js.org/d3.v4.min.js"></script>


    <script>
    // set the dimensions and margins of the graph
    var width = 450
        height = 450
        margin = 40

    // The radius of the pieplot is half the width or half the height (smallest one) minus margin.
    var radius = Math.min(width, height) / 2 - margin

    // append the svg object to the div called 'chart'
    var svg = d3.select("#chart")
      .append("svg")
        .attr("width", width)
        .attr("height", height)
      .append("g")
        .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");


    // Parse the Data
    d3.json("/data/all-facet-digitized.json", function(data) {

      // set the color scale
      var color = d3.scaleOrdinal()
        .domain(["true","false"])
        .range(d3.schemeDark2);

      // Compute the position of each group on the pie:
      var pie = d3.pie()
        .sort(null) // Do not sort group by size
        .value(function(d) {return d.count; })
      var data_ready = pie(d3.entries(data))

      // The arc generator
      var arc = d3.arc()
        .innerRadius(radius * 0.5)         // This is the size of the donut hole
        .outerRadius(radius * 0.8)

      // Another arc that won't be drawn. Just for labels positioning
      var outerArc = d3.arc()
        .innerRadius(radius * 0.9)
        .outerRadius(radius * 0.9)

      // Build the pie chart: Basically, each part of the pie is a path that we build using the arc function.
      svg
        .selectAll('allSlices')
        .data(data_ready)
        .enter()
        .append('path')
        .attr('d', arc)
        .attr('fill', function(d){ return(color(d.facet)) })
        .attr("stroke", "white")
        .style("stroke-width", "2px")
        .style("opacity", 0.7)

      // Add the polylines between chart and labels:
      svg
        .selectAll('allPolylines')
        .data(data_ready)
        .enter()
        .append('polyline')
          .attr("stroke", "black")
          .style("fill", "none")
          .attr("stroke-width", 1)
          .attr('points', function(d) {
            var posA = arc.centroid(d) // line insertion in the slice
            var posB = outerArc.centroid(d) // line break: we use the other arc generator that has been built only for that
            var posC = outerArc.centroid(d); // Label position = almost the same as posB
            var midangle = d.startAngle + (d.endAngle - d.startAngle) / 2 // we need the angle to see if the X position will be at the extreme right or extreme left
            posC[0] = radius * 0.95 * (midangle < Math.PI ? 1 : -1); // multiply by 1 or -1 to put it on the right or on the left
            return [posA, posB, posC]
          })

      // Add the polylines between chart and labels:
      svg
        .selectAll('allLabels')
        .data(data_ready)
        .enter()
        .append('text')
          .text( function(d) { console.log(d.facet) ; return d.facet} )
          .attr('transform', function(d) {
              var pos = outerArc.centroid(d);
              var midangle = d.startAngle + (d.endAngle - d.startAngle) / 2
              pos[0] = radius * 0.99 * (midangle < Math.PI ? 1 : -1);
              return 'translate(' + pos + ')';
          })
          .style('text-anchor', function(d) {
              var midangle = d.startAngle + (d.endAngle - d.startAngle) / 2
              return (midangle < Math.PI ? 'start' : 'end')
          })
      })

    </script>


//设置图形的尺寸和边距
var宽度=450
高度=450
保证金=40
//pieplot的半径是宽度的一半或高度的一半(最小值)减去边距。
变量半径=数学最小值(宽度、高度)/2-边距
//将svg对象附加到名为“chart”的div中
var svg=d3。选择(“图表”)
.append(“svg”)
.attr(“宽度”,宽度)
.attr(“高度”,高度)
.附加(“g”)
.attr(“变换”、“平移”(+width/2+)、“+height/2+”);
//解析数据
d3.json(“/data/all-facet digized.json”),函数(数据){
//设置颜色比例
var color=d3.scaleOrdinal()
.domain([“真”、“假”])
.范围(d3.schemeDark2);
//计算每个组在饼图上的位置:
var pie=d3.pie()
.sort(null)//不按大小对组进行排序
.value(函数(d){返回d.count;})
var data_ready=pie(d3.条目(数据))
//电弧发生器
var arc=d3.arc()
.innerRadius(半径*0.5)//这是圆环孔的大小
.外表面(半径*0.8)
//另一个不会绘制的弧。仅用于标签定位
var outerArc=d3.arc()
.内半径(半径*0.9)
.外表面(半径*0.9)
//构建饼图:基本上,饼图的每个部分都是我们使用arc函数构建的路径。
svg
.selectAll('allSlices')
.数据(数据准备就绪)
.输入()
.append('路径')
.attr('d',弧)
.attr('fill',函数(d){return(color(d.facet))})
.attr(“笔划”、“白色”)
.style(“笔划宽度”、“2px”)
.样式(“不透明度”,0.7)
//在图表和标签之间添加多段线:
svg
.selectAll('所有多段线')
.数据(数据准备就绪)
.输入()
.append('多段线')
.attr(“笔划”、“黑色”)
.style(“填充”、“无”)
.attr(“笔划宽度”,1)
.attr('points',函数(d){
var posA=arc.centroid(d)//在切片中插入线
var posB=outerArc.centroid(d)//换行:我们使用另一个专门为此构建的弧生成器
var posC=outerArc.centroid(d);//标签位置=几乎与posB相同
var midangle=d.startAngle+(d.endAngle-d.startAngle)/2//我们需要这个角度来确定X位置是在最右边还是最左边
posC[0]=半径*0.95*(midangle
“我的结果”渲染为空白:


    <div id="chart">
      <svg width="450" height="450">
        <g transform="translate(225,225)"></g>
      </svg>
    </div>



d3 v4中不存在
schemeDark2
。我已将其替换为
schemecategory 10

  var color = d3.scaleOrdinal()
    .domain(["true","false"])
    .range(d3.schemeCategory10);
因为您有一个对象数组,所以不需要
d3.entries
。它获取一个对象并将其转换为数组,其中每个键都是数组的一项。但是,因为这里已经有一个数组,所以可以直接将它放入
pie()

现在您已经获得了数据,您可以在任何函数上访问它:尝试放置
console.log(data\u ready)
以查看可用的数据。您将看到每个对象的数据都绑定为
.data
属性
pie()
获取一个数组,并将其置于便于制作饼图的格式中

假设我们想要访问facet属性:我们将以
item.data.facet
的形式访问它。因此,在您的函数中,要访问,您可以执行以下操作:

  svg
    .selectAll('allSlices')
    .data(data_ready)
    .enter()
    .append('path')
    .attr('d', arc)
    .attr('fill', function(d){ return(color(d.data.facet)) })

//设置图形的尺寸和边距
可变宽度=450
高度=450
保证金=40
//pieplot的半径是宽度的一半或高度的一半(最小值)减去边距。
变量半径=数学最小值(宽度、高度)/2-边距
//将svg对象附加到名为“chart”的div中
var svg=d3。选择(“图表”)
.append(“svg”)
.attr(“宽度”,宽度)
.attr(“高度”,高度)
.附加(“g”)
.attr(“变换”、“平移”(+width/2+)、“+height/2+”);
//解析