如何使用HighchartsJS在圆环图的中心添加自定义文本?

8mmmxcuj  于 9个月前  发布在  Highcharts
关注(0)|答案(1)|浏览(83)

enter image description here我可以在highcharts中得到一个圆环图,这很容易。我不能得到一些自定义文本在中间的甜甜圈图表张贴在所附的图像。
我试着问HighchartsGPT同样的,它提供了以下代码:

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;
        }
      }
    }
  }
});

这在图像中未按预期渲染。相反,我得到了一个折线图作为输出。

ua4mk5z4

ua4mk5z41#

您需要将chart.plotLeftchart.plotTop添加到center值:

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;
        }
      }
    }
  }

示例:https://jsfiddle.net/BlackLabel/urfm8gve/
API引用:https://api.highcharts.com/highcharts/chart.events.render

相关问题