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

fiei3ece  于 2022-11-07  发布在  Chart.js
关注(0)|答案(4)|浏览(349)
  • Chart.js 2.6.0*

我需要呈现一个如下所示的图表:

始终显示所有工具提示不是一种可接受的方式,因为它们不会以正确的方式进行渲染:

不幸的是,我还没有找到一个解决方案。我试过 piece-label 插件,但这也有同样的问题,因为它的标签重叠,我不能隐藏某些标签。
下面是创建图表的代码,使用 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]);
}

结果是:

cld4siwp

cld4siwp1#

有一个新插件(一年以来),名为chartjs-plugin-piechart-outlabels
仅导入源
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-piechart-outlabels"></script>
并将其与outlabeledPie类型一起使用

var randomScalingFactor = function() {
return Math.round(Math.random() * 100);
};
var ctx = document.getElementById("chart-area").getContext("2d");
var myDoughnut = new Chart(ctx, {
type: 'outlabeledPie',
data: {
labels: ["January", "February", "March", "April", "May"],
...
plugins: {
        legend: false,
        outlabels: {
           text: '%l %p',
           color: 'white',
           stretch: 45,
           font: {
               resizable: true,
               minSize: 12,
               maxSize: 18
           }
        }
     }
})
bn31dyow

bn31dyow2#

我不能找到一个确切的插件,但我做一个。

const data = {
        labels: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
        datasets: [
          {
            data: [1, 2, 3, 4, 5, 6],
            backgroundColor: [
              "#316065",
              "#1A7F89",
              "#2D9CA7",
              "#2D86A7",
              "#1167A7",
              "#142440",
            ],
            borderColor: [
              "#316065",
              "#1A7F89",
              "#2D9CA7",
              "#2D86A7",
              "#1167A7",
              "#142440",
            ],
          },
        ],
      };

      // pieLabelsLine plugin
      const pieLabelsLine = {
        id: "pieLabelsLine",
        afterDraw(chart) {
          const {
            ctx,
            chartArea: { width, height },
          } = chart;

          const cx = chart._metasets[0].data[0].x;
          const cy = chart._metasets[0].data[0].y;

          const sum = chart.data.datasets[0].data.reduce((a, b) => a + b, 0);

          chart.data.datasets.forEach((dataset, i) => {
            chart.getDatasetMeta(i).data.forEach((datapoint, index) => {
              const { x: a, y: b } = datapoint.tooltipPosition();

              const x = 2 * a - cx;
              const y = 2 * b - cy;

              // draw line
              const halfwidth = width / 2;
              const halfheight = height / 2;
              const xLine = x >= halfwidth ? x + 20 : x - 20;
              const yLine = y >= halfheight ? y + 20 : y - 20;

              const extraLine = x >= halfwidth ? 10 : -10;

              ctx.beginPath();
              ctx.moveTo(x, y);
              ctx.arc(x, y, 2, 0, 2 * Math.PI, true);
              ctx.fill();
              ctx.moveTo(x, y);
              ctx.lineTo(xLine, yLine);
              ctx.lineTo(xLine + extraLine, yLine);
              // ctx.strokeStyle = dataset.backgroundColor[index];
              ctx.strokeStyle = "black";
              ctx.stroke();

              // text
              const textWidth = ctx.measureText(chart.data.labels[index]).width;
              ctx.font = "12px Arial";
              // control the position
              const textXPosition = x >= halfwidth ? "left" : "right";
              const plusFivePx = x >= halfwidth ? 5 : -5;
              ctx.textAlign = textXPosition;
              ctx.textBaseline = "middle";
              // ctx.fillStyle = dataset.backgroundColor[index];
              ctx.fillStyle = "black";

              ctx.fillText(
                ((chart.data.datasets[0].data[index] * 100) / sum).toFixed(2) +
                  "%",
                xLine + extraLine + plusFivePx,
                yLine
              );
            });
          });
        },
      };
      // config
      const config = {
        type: "pie",
        data,
        options: {
          maintainAspectRatio: false,
          layout: {
            padding: 30,
          },
          scales: {
            y: {
              display: false,
              beginAtZero: true,
              ticks: {
                display: false,
              },
              grid: {
                display: false,
              },
            },
            x: {
              display: false,
              ticks: {
                display: false,
              },
              grid: {
                display: false,
              },
            },
          },
          plugins: {
            legend: {
              display: false,
            },
          },
        },
        plugins: [pieLabelsLine],
      };

      // render init block
      const myChart = new Chart(document.getElementById("myChart"), config);

https://codepen.io/BillDou/pen/oNoGBXb

kpbpu008

kpbpu0083#

真实的的问题在于当切片很小时标签的重叠。你可以使用PieceLabel.js,它通过隐藏标签来解决重叠标签的问题。你提到你不能隐藏标签所以使用图例,它将显示所有切片的名称
或者,如果你想要确切的行为,你可以去与highcharts,但它需要许可证的商业用途。
第一个
Fiddle演示

ffscu2ro

ffscu2ro4#

我决定:我们将脚本添加到全局文件:

if(window.Chartist && Chartist.Pie && !Chartist.Pie.prototype.resolveOverlap) {
        Chartist.Pie.prototype.resolveOverlap = function() {
            this.on('draw', function(ctx) {
                if(ctx.type == 'label') {
                    let gText = $(ctx.group._node).find('text');
                    let ctxHeight = ctx.element.height();
                    gText.each(function(index, ele){
                        let item = $(ele);
                        let diff = ctx.element.attr('dy') - item.attr('dy');
                        if(diff == 0) {
                            return false;
                        }
                        if(Math.abs(diff) < ctxHeight) {
                            ctx.element.attr({dy: ctx.element.attr('dy') - ctxHeight});
                        }
                    });
                }
            });
        };
    }

然后:

new Chartist.Pie(element, data, options).resolveOverlap();

相关问题