首页 > 解决方案 > 将数据从 JSON 导入 D3 并在饼图部分显示

问题描述

我有一个饼图出现在这里https://imgur.com/MDdUKsQ,试图重现此图像:https ://imgur.com/rNKtAUD

一直在努力让每个部分出现大百分比的标题。我曾考虑过制作 HTML 元素并长期进行,但最好从 JSON 文件中提取它们,如下所示。我将如何做到这一点?使用 D3 的 V6

JSON:

[
    {"name": "Less than a month","total": 100,"Percent":1.39},
    {"name": "1-3 months","total": 290,"Percent":20.83},
    {"name": "3-6 months","total": 400,"Percent":56.94},
    {"name": "6-12 months","total": 600,"Percent":5.56},
    {"name": "More than 12 months","total": 300,"Percent":15.28},
    {"name": "There won't be business as usual","total": 100,"Percent":15.28}

    ]
// get data from JSON
function getData() {
    d3.json("./data/piedata.json", function(d) {return d}).then(drawPie)
}

getData()

//draw the pie chart
function drawPie(data) {
    colourScale.domain(data.map(d=>d.name))
    const angles = pie(data)
    const paths = pieCanvas.selectAll("path").data(angles)
    paths.enter().append("path").attr("d", arcPath).attr("class","arc")
                 .attr("stroke","white").attr("fill", d=>colourScale(d.data.name))
    //add legend
    const legend = svg.selectAll('.legend').data(colourScale.domain()).enter().append('g')                                          
          .attr('class', 'legend').attr('transform', function(d, i) {                    
           const height = legendRectSize + legendSpacing          
           const offset =  height * colourScale.domain().length / 3
           const horz = 20 * legendRectSize                       
           const vert = i * height - offset + 260                      
           return 'translate(' + horz + ',' + vert + ')'});  

    legend.append('rect').attr('width', legendRectSize).attr('height', legendRectSize)                        
          .style('fill', colourScale).style('stroke', colourScale)                      
          
    legend.append('text').attr('x', legendRectSize + legendSpacing)           
          .attr('y', legendRectSize - legendSpacing).text(function(d) { return d })                      
      }

标签: javascriptd3.js

解决方案


试试 d3.json("./data/piedata.json", function(d){ drawPie(d); })


推荐阅读