在d3.js v5中向饼图添加标签和折线

时间:2020-09-02 14:22:18

标签: javascript d3.js

我希望在饼图中添加如下所示的线和标签:enter image description here

这是来自http://bl.ocks.org/dbuezas/9306799

我不知道如何在V5中将线条和标签添加到饼图中。

到目前为止,这是我的代码:

HTML

<div id="pie-chart"></div>

JS

const canvas1 = d3.select('#pie-chart');

const svg1 = canvas1.append('svg')
  .attr('preserveAspectRatio', 'xMinYMin meet')
  .attr('viewBox', '0 0 450 350')
  .classed('svg-content', true);

const margin1 = {top: 10, right: 2, bottom: 2, left: 2}
const graphWidth1 = 450 - margin1.left - margin1.right
const graphHeight1 = 450 - margin1.top - margin1.bottom

const mainCanvas = svg1.append('g')
  .attr('width', graphWidth1 / 2)
  .attr('height', graphHeight1 / 2)
  .attr('transform', `translate(${margin1.left + 220}, ${margin1.top + 140})`);

  //Define ordinal scale
  const colorScale = d3.scaleOrdinal(d3.schemeBlues[6]) //may need to chang back to d3.schemeDark2  

  //parse json
  function getJSONData() {
    d3.json('alpha.json', function(d){
      return d;
    }).then(drawPieChart);
  }

  //create pie chart
  const pie = d3.pie()
    .sort(null)
    .value(data => data.units)//change data field here eg count or weight.

  //set radius
  const arcPath = d3.arc()
    .outerRadius(150)
    .innerRadius(60) //change these for size of pie and size of inner hole.

  getJSONData();

  function drawPieChart(data){
    colorScale.domain(data.map(d => d.units));

    const angles = pie(data);
    console.log(data)

    //create the actual paths on screen
    const paths = mainCanvas.selectAll('path')
      .data(angles)

      paths.enter()
        .append('path')
        .attr('class', 'arc')
        .attr('stroke', 'black')
        .attr('fill', d => colorScale(d.data.units))
        .attr('d', arcPath)      

      paths.enter()
        .append('text')
        .text(function(d){ return d.data.sizeBand})
        // .text(function(d){ return "sizeband " + d.data.sizeBand})
        .attr("transform", function(d) { return "translate(" + arcPath.centroid(d) + ")";  })
        .style("text-anchor", "middle")
        .attr("dy", ".0em")
        .attr("dx", ".0em")
        .style("font-size", 10)
        .style('font-weight', 600);
      }

alpha.JSON:

[
{"sizeBand": "25-29", "units": 56659},
{"sizeBand": "30-34", "units": 137201},
{"sizeBand": "35-39", "units": 201630},
{"sizeBand": "40-44", "units": 211939},
{"sizeBand": "45-49", "units": 225547},
{"sizeBand": "50-54", "units": 45368}
]

这给了我

enter image description here

对不起,找不到将JSON添加到小提琴的方法。 将文本显示在饼图的外部将非常出色,并且添加行将是一个额外的好处。

非常感谢您的帮助。

谢谢。

0 个答案:

没有答案