简体   繁体   English

将数据从 JSON 导入 D3 并在饼图部分显示

[英]Importing data from JSON into D3 and displaying it on pie chart sections

I have a pie graph coming along here https://imgur.com/MDdUKsQ , trying to reproduce this image: https://imgur.com/rNKtAUD我有一个饼图出现在这里https://imgur.com/MDdUKsQ ,试图重现此图像: https://imgur.com/rNKtAUD

Been struggling a bit with trying to get the large percentage headers to appear for each section.一直在努力让每个部分出现大百分比的标题。 I gave thought to making HTML elements and doing it the long way, but it would be nice to pull them in from a JSON file as shown below.我考虑过制作 HTML 元素并长期进行,但最好从 JSON 文件中提取它们,如下所示。 How would I accomplish this?我将如何做到这一点? Using V6 of D3使用 D3 的 V6

JSON: 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 })                      
      }

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

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

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