將資料標籤移至圓餅圖或圓環圖之外 - Chart.js
P粉356128676
P粉356128676 2023-11-23 15:07:41
0
1
868

我正在開發一個大型應用程序,將標籤放置在圖表本身之外的餅圖或圓環圖上會非常有幫助。

這個插件,outerLabels 正是我正在尋找的,但我無法讓它輸出任何內容。

我一直無法找到使用 Chart.js 完成此任務的方法,這就是我現在所堅持的方法。

我已經導入了插件 從'chartjs-plugin-outerlabels'導入{}; 也喜歡 import 'chartjs-plugin-outerlabels';

以下是我如何設定圖表選項的範例:

function getPieChartOptions(chartTitle: string) {
    const options: ChartOptions = {
        responsive: true,
        plugins: {
            outerLabels: {
                fontNormalSize: 12,
                fontNormalFamily: 'sans-serif',
            },
            legend: {
                display: true,
                labels: {
                    usePointStyle: true,
                    font: {
                        family: 'sans-serif',
                        size: 12,
                    }
                }
            },
            title: {
                display: true,
                text: chartTitle,
                color: 'black',
                padding: 5,
                font: {
                    size: 16,
                    family: 'sans-serif',
                }
            },
            datalabels: {
                color: 'white',
                formatter: commas.format,
            }
        },
    };
    return options;
}

以下是專案本身內的圓環圖範例:

如果有人可以幫助讓這個外掛正常運作,或有其他解決方案來解決這個問題,我們將不勝感激!

P粉356128676
P粉356128676

全部回覆(1)
P粉762730205

這對我來說沒有 datalabels 欄位(因為它需要安裝 Chartjs-plugin-datalabels.js 函式庫)。

所以基本上是 ChartOptions 設定與您提供的設定類似。

import 'chartjs-plugin-outerlabels';

getPieChartOptions(chartTitle: string) {
  const options: ChartOptions = {
    responsive: true,
    plugins: {
      outerLabels: {
        fontNormalSize: 12,
        fontNormalFamily: 'sans-serif',
      },
      legend: {
        display: true,
        labels: {
          usePointStyle: true,
          font: {
            family: 'sans-serif',
            size: 12,
          },
        },
      },
      title: {
        display: true,
        text: chartTitle,
        color: 'black',
        padding: 5,
        font: {
          size: 16,
          family: 'sans-serif',
        },
      },
      tooltip: {
        enabled: false,
      },
    },
  };
  return options;
}

這就是如何將圖表渲染到畫布元素。

@ViewChild('MyChart', { static: true }) chart: ElementRef;

ngAfterViewInit() {
  const ctx = this.chart.nativeElement.getContext('2d');
  new Chart(ctx, {
    type: 'doughnut',
    data: {
      labels: [['Download', 'Sales'], ['In', 'Store', 'Sales'], 'Mail Sales'],
      datasets: [
        {
          data: [300, 500, 100],
        },
      ],
    },
    options: this.getPieChartOptions('doughnut'),
  } as ChartConfiguration).draw;
}

示範 @ StackBlitz

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!