将数据标签移动到饼图或圆环图之外 - Chart.js
P粉356128676
P粉356128676 2023-11-23 15:07:41
0
1
867

我正在开发一个大型应用程序,将标签放置在图表本身之外的饼图或圆环图上会非常有帮助。

这个插件,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学习者快速成长!