Highcharts饼图注释未居中

时间:2020-01-15 23:21:43

标签: highcharts

我有2个饼图,分别对应于2个系列。我想在每个系列下添加一个标题,但不想使用title属性,因为每个Highcharts组件仅获得一个标题。我选择使用注释,并且该方法有效,这需要我手动为注释标签指定x和y坐标。我正在使用公式来计算这些确切位置。但是,当我渲染注释时,它们似乎并没有在每个图表的中间完全对齐。

我的图表选项如下:

const width = 700
const height = 200

Highcharts.chart('container', {
chart: {
    type: 'pie',
    width,
    height
},

plotOptions: {
    pie: {
        dataLabels: {
            enabled: false
        }
    }
},
annotations: [{
    labels: [{
        point: {
            x: 0.33 * width,
            y: height
        },
        text: "centered"
    }]
}, {
    labels: [{
        point: {
            x: 0.635 * width,
            y: height
        },
        text: "also centered"
    }]
}],
series: [
    {
        center: ['33%', '50%'],
        type: 'pie',
        data: [
            ['Firefox',   44.2],
            ['IE7',       26.6],
            ['IE6',       20],
            ['Chrome',    3.1],
            ['Other',    5.4]
        ]
    },
    {
        center: ['66%', '50%'],
        type: 'pie',
        data: [
            ['Firefox',   44.2],
            ['IE7',       26.6],
            ['IE6',       20],
            ['Chrome',    3.1],
            ['Other',    5.4]
        ]
    }]
});

这是现在的样子:https://jsfiddle.net/0cfztdms/

这是我想要不对x位置进行硬编码而要实现的目标: Pie charts with centered annotations

2 个答案:

答案 0 :(得分:0)

我认为,通过使用SVGRendere工具而不是使用注释功能,将是一种更好的解决方案。

演示:https://jsfiddle.net/BlackLabel/L08bvngk/

render() {
  let chart = this;

  chart.series.forEach((s, i) => {
    if (chart['label' + i]) {
      chart['label' + i].destroy();
    }
    chart['label' + i] = chart.renderer.label('testtestestest', 0, 0)
      .css({
        color: '#FFFFFF'
      })
      .attr({
        fill: 'rgba(0, 0, 0, 0.75)',
        padding: 8,
        r: 5,
        zIndex: 6
      })
      .add();
    //center the label
    chart['label' + i].translate(s.center[0] + chart.plotLeft - chart['label' + i].getBBox().width / 2, chart.plotHeight)
  })
}

API:https://api.highcharts.com/class-reference/Highcharts.SVGRenderer#label

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

答案 1 :(得分:0)

我想出了一种方法,可以使标签居中,而无需使用Highcharts annotations module进行手动计算。设置anchorX = 'center'anchorY = 'middle'(这些道具来自注释模块)将自动为您居中注释。 Read more here

const width = 600;

annotations: [{
  labels: [{
    point: {
      x: (1 / numberOfCharts + 1) * width,
      y: 200,
      anchorX: 'center',
      anchorY: 'middle'
    },
    text: 'Label 1'
  }, {
    point: {
      x: (1 / numberOfCharts + 1) * 2 * width,
      y: 200,
      anchorX: 'center',
      anchorY: 'middle'
    },
    text: 'Label 2'
  }
}]
相关问题