【问题标题】:Highcharts: How to align text label middle center of pie chartHighcharts:如何对齐饼图的文本标签中间中心
【发布时间】:2019-04-19 19:55:04
【问题描述】:

我编辑了 thomas_rz 的 codepen.io

https://codepen.io/thomas_rz/pen/vXyoaK?editors=1010

document.addEventListener("DOMContentLoaded", function() {
  var chart1 = new Highcharts.Chart({
    chart: {
      type: 'pie',
      renderTo: 'container'
    },
    title: {
      verticalAlign: 'middle',
      floating: true,
      text: 'CENTERED<br>TEXT'
    },
    plotOptions: {
      pie: {
        innerSize: '50%',
        dataLabels: {
          align: 'right',
          distance: 10,
          connectorWidth: 0
        }
      }
    },

    series: [{
      data: [
        ['Firefox', 44.2],
        ['IE7', 26.6],
        ['IE6', 20],
        ['Chrome', 3.1],
        ['Other', 5.4]
      ]
    }]
  });
});

并返回此图表。

但我需要这个图表,文本对齐饼图的中间中心

【问题讨论】:

    标签: highcharts


    【解决方案1】:

    计算中的Highcharts 没有考虑带有&lt;br&gt; 标签的正确标题高度。可以在render事件中计算标题的正确位置:

    chart: {
        ...,
        events: {
            render: function() {
                var title = this.title;
                title.attr({
                    y: this.plotTop + this.plotHeight / 2 +
                        title.getBBox().height / 2 -
                        parseInt(title.styles.fontSize)
                });
            }
        }
    },
    

    现场演示: http://jsfiddle.net/BlackLabel/vnsp1ybz/

    API 参考:

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

    https://api.highcharts.com/class-reference/Highcharts.SVGElement#attr

    【讨论】:

    • 非常感谢您的帮助,但“Chrome”和“其他”仍然未对齐(偏离切片的轴)。
    【解决方案2】:

    数据标签对齐说明:

    默认情况下,Pie 的数据标签不支持这种外观。

    在 Highcharts 中,数据标签的位置与其连接器的位置密切相关。您在演示中禁用了连接器,这就是这些标签看起来错位的原因。

    算法始终确保标签的 VERTICAL 边缘的中心(标签被视为一个盒子)接触连接器的末端。您的要求是连接器应该能够接触标签框的ANY部分(垂直或水平):

    没有高级的Highcharts核心修改是无法实现的。

    解决方法:

    通过重新定义两个核心功能,我能够实现非常接近您需要的东西:

    (function(H) {
      H.seriesTypes.pie.prototype.dataLabelPositioners.radialDistributionX = function(series, point) {
        return point.labelPosition.natural.x - (point.half ? -0.5 : 0.5) * point.dataLabel.width;
      }
      H.seriesTypes.pie.prototype.dataLabelPositioners.radialDistributionY = function(point) {
        return point.labelPosition.natural.y;
      }
    })(Highcharts);
    

    现场演示http://jsfiddle.net/BlackLabel/htk40ena/

    上面的代码强制 Highcharts 改变连接器接触标签的位置。请注意,连接器在我的演示中没有意义(尝试启用它们)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-05
      相关资源
      最近更新 更多