Search code examples
javascriptdc.jscrossfilter

How to show value in center of pie chart using dc.js


I have created a pie chart using dc.js which looks like this pie chart

Here I want to show some value in between of pie chart in the circular white space area. I have not found any example related to this.

I am adding my code below. Thank you.

  let data = [
    {
        productCount: 1,
        customer : 200 
    },
    {
        productCount: 2,
        customer : 100 
    },
    {
        productCount: 3,
        customer : 300 
    },
    {
        productCount: 4,
        customer : 400 
    },
    {
        productCount: 5,
        customer : 560 
    },
    {
        productCount: 6,
        customer : 2100 
    },
]

            let totalCustomerArray = data.map(data => data.customer);
            let totalCustomer = totalCustomerArray.reduce((a, b) => a + b);
            let ndx = crossfilter(data);
            let all = ndx.groupAll();

            let productCountDimension = ndx.dimension(d => d.productCount);
            let groupCustomer = productCountDimension.group().reduceSum(d => d.customer);

            const pie = dc.pieChart('.pie-chart');
            pie
                .width(400)
                .height(400)
                .radius(140)
                .innerRadius(90)
                .dimension(productCountDimension)
                .group(groupCustomer)
                .on('pretransition', (chart) => {
                    pie.selectAll('text.pie-slice').text(d =>  (
                    dc.utils.printSingleValue((d.endAngle - d.startAngle) / (2 * Math.PI) * 100) + '%'
                    ))
                })

            pie.render();

In the above code on line number two the variable name totalCustomer contains the total customer sum which needs to be placed between the pie chart circle in white circular space.


Solution

  • Use d3 (which you are currently using) to append a text element to the svg pie chart. Just select the tag and then append the element to it. You can also use <tpsan></tspan>

    var svg = d3.select("svg"); // select the svg element where you are putting your pie chart.
    svg.append("text") // appent the "text" element
      .attr("x", 220) // x position
      .attr("y", 220) // y position
      .text("1234") // the text content