首页 文章

chart.js:在饼图外显示标签

提问于
浏览
12

chart.js 2.6.0

我需要渲染一个如下所示的图表:

enter image description here

始终显示所有工具提示是不可接受的方式,因为它们不会以适当的方式呈现:

enter image description here

不幸的是,我无法尝试使用片标签插件,但这有同样的问题,因为它隐藏了某些标签 .

这是代码,它使用piece-label创建我的图表以将标签定位在切片上方:

private createStatusChart(): void {
    const chartData = this.getStatusChartData();

    if (!chartData) {
        return;
    }

    const $container = $(Templates.Dashboard.ChartContainer({
        ContainerID: 'chart-status',
        HeaderText: 'Status'
    }));

    this._$content.append($container);

    const legendOptions =
        new Model.Charts.LegendOptions()
            .SetDisplay(false);

    const pieceLabelOptions =
        new Model.Charts.PieceLabelOptions()
            .SetRender('label')
            .SetPosition('outside')
            .SetArc(true)
            .SetOverlap(true);

    const options =
         new Model.Charts.Options()
             .SetLegend(legendOptions)
             .SetPieceLabel(pieceLabelOptions);

    const chartDefinition = new Model.Charts.Pie(chartData, options);
    const ctx = this._$content.find('#chart-status canvas').get(0);

    const chart = new Chart(ctx, chartDefinition);
}

private getStatusChartData(): Model.Charts.PieChartData {
    if (!this._data) {
        return;
    }

    const instance = this;
    const data: Array<number> = [];
    const labels: Array<string> = [];
    const colors: Array<string> = [];

    this._data.StatusGroupings.forEach(sg => {
        if (!sg.StatusOID) {
            data.push(sg.Count);
            labels.push(i18next.t('Dashboard.NoStateSet'));
            colors.push('#4572A7');

            return;
        }

        const status = DAL.Properties.GetByOID(sg.StatusOID);

        data.push(sg.Count);
        labels.push(status ? status.Title : i18next.t('Misc.Unknown'));
        colors.push(status ? status.Color : '#fff');
    });

    const dataset = new Model.Charts.Dataset(data).setBackgroundColor(colors);

    return new Model.Charts.PieChartData(labels, [dataset]);
}

结果:

enter image description here

2 回答

  • 1

    真正的问题在于切片很小时标签的重叠 . 您可以使用PieceLabel.js通过隐藏标签来解决重叠标签的问题 . 你提到你 cannot hide labels 所以使用图例,它会显示所有切片的名称

    或者,如果您想要确切的行为,您可以使用highcharts,但它需要许可证才能用于商业用途 .

    var randomScalingFactor = function() {
      return Math.round(Math.random() * 100);
    };
    var ctx = document.getElementById("chart-area").getContext("2d");
    var myDoughnut = new Chart(ctx, {
      type: 'pie',
      data: {
        labels: ["January", "February", "March", "April", "May"],
        datasets: [{
          data: [
            250,
            30,
            5,
            4,
            2,
    
          ],
          backgroundColor: ['#ff3d67', '#ff9f40', '#ffcd56', '#4bc0c0', '#999999'],
          borderColor: 'white',
          borderWidth: 5,
        }]
      },
      showDatapoints: true,
      options: {
        tooltips: {
          enabled: false
        },
        pieceLabel: {
          render: 'label',
          arc: true,
          fontColor: '#000',
          position: 'outside'
        },
        responsive: true,
        legend: {
          position: 'top',
        },
        title: {
          display: true,
          text: 'Testing',
          fontSize: 20
        },
        animation: {
          animateScale: true,
          animateRotate: true
        }
      }
    });
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
    <script src="https://cdn.rawgit.com/emn178/Chart.PieceLabel.js/master/build/Chart.PieceLabel.min.js"></script>
    <canvas id="chart-area"></canvas>
    

    Fiddle演示

  • -1
    // I think this script should be solve your problem 
    
                <script src="https://code.highcharts.com/highcharts.js"></script>
                <script src="https://code.highcharts.com/modules/exporting.js"></script>
                <div id="container" style="min-width: 310px; height: 400px; max-width: 600px; margin: 0 auto"></div>
            <script>Highcharts.chart('container', { chart: {
                        plotBackgroundColor: null,
                        plotBorderWidth: null,
                        plotShadow: false,
                        type: 'pie'
                    },
                    title: {
                        text: 'Browser market shares January, 2015 to May, 2015'
                    },
                    tooltip: {
                        pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
                    },
                    plotOptions: {
                        pie: {
                            allowPointSelect: true,
                            cursor: 'pointer',
                            dataLabels: {
                                enabled: true,
                                format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                                style: {
                                    color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                                }
                            }
                        }
                    },
                    series: [{
                        name: 'Brands',
                        colorByPoint: true,
                        data: [{
                            name: 'Microsoft Internet Explorer',
                            y: 56.33
                        }, {
                            name: 'Chrome',
                            y: 24.03,
                            sliced: true,
                            selected: true
                        }, {
                            name: 'Firefox',
                            y: 10.38
                        }, {
                            name: 'Safari',
                            y: 4.77
                        }, {
                            name: 'Opera',
                            y: 0.91
                        }, {
                            name: 'Proprietary or Undetectable',
                            y: 0.2
                        }]
                    }]
                });
    
                </script>
       http://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/demo/pie-basic/
    

相关问题