Search code examples
highchartsvisualizationdonut-chart

How do you add custom text in the center of a Donut Chart using HighchartsJS?


enter image description here I'm able to get a donut chart in highcharts, which is easy. I'm not able to get some custom text in the middle of the donut chart as posted in the attached image.

I tried asking HighchartsGPT for the same, it provided the following code:

Highcharts.chart('container', {
  chart: {
    type: 'pie'
  },
  title: {
    text: 'Donut Chart with Custom Text'
  },
  plotOptions: {
    pie: {
      innerSize: '50%',
      dataLabels: {
        enabled: false
      }
    }
  },
  series: [{
    name: 'Brands',
    colorByPoint: true,
    data: [{
      name: 'Chrome',
      y: 61.41,
      color: '#FF0000'
    }, {
      name: 'Firefox',
      y: 11.84,
      color: '#00FF00'
    }, {
      name: 'Internet Explorer',
      y: 10.85,
      color: '#0000FF'
    }, {
      name: 'Safari',
      y: 4.67,
      color: '#FFFF00'
    }, {
      name: 'Edge',
      y: 4.18,
      color: '#FF00FF'
    }, {
      name: 'Other',
      y: 7.05,
      color: '#00FFFF'
    }]
  }],
  // Add custom text in the center of the donut chart
  chart: {
    events: {
      render: function() {
        var chart = this,
          center = chart.series[0].center,
          renderer = chart.renderer,
          text;

        if (!chart.customText) {
          text = renderer.text(
            'Custom Text',
            center[0],
            center[1]
          ).attr({
            align: 'center',
            verticalAlign: 'middle',
            style: {
              fontSize: '20px',
              fontWeight: 'bold',
              color: '#000000'
            }
          }).add();
          chart.customText = text;
        }
      }
    }
  }
});

This did not render as expected in the image. Instead, I got a line chart as output.


Solution

  • You need to add chart.plotLeft and chart.plotTop to the center values:

      chart: {
        type: 'pie',
        events: {
          render: function() {
            var chart = this,
              center = chart.series[0].center,
              renderer = chart.renderer,
              text;
    
            if (!chart.customText) {
              text = renderer.text(
                'Custom Text',
                center[0] + chart.plotLeft,
                center[1] + chart.plotTop
              ).attr({
                align: 'center',
                verticalAlign: 'middle',
                style: {
                  fontSize: '20px',
                  fontWeight: 'bold',
                  color: '#000000'
                }
              }).add();
              chart.customText = text;
            }
          }
        }
      }
    

    Live example: https://jsfiddle.net/BlackLabel/urfm8gve/

    API Reference: https://api.highcharts.com/highcharts/chart.events.render