如何使用JavaScript或Angular在PrimeNG(图表)饼图中显示值

时间:2019-12-19 10:30:51

标签: javascript angular charts chart.js primeng

我已经从PRIMENG CHART PLUGIN中导入了饼图

我需要在饼图中显示值

以下是我的代码,请参阅

**In app.component.html**

<div style="display: block">
    <p-chart type="pie" [data]="data"></p-chart>
</div>

**In app.component.ts**

export class PieChartDemo {

    data: any;

    constructor() {
        this.data = {
            labels: ['A', 'B', 'C'],
            datasets: [{
                data: [300, 50, 100],
                backgroundColor: [
                    "#FF6384",
                    "#36A2EB",
                    "#FFCE56"
                ],
                hoverBackgroundColor: [
                    "#FF6384",
                    "#36A2EB",
                    "#FFCE56"
                ]
            }]
        };
    }
}

在图像中我附上了图表,没有显示任何值

如果为负数-50

正数-50

这些值应显示在图形内

实际结果:

到目前为止,这些值尚未显示在图形内部

预期结果:

这些值应显示在图形内部 The graph UI without the values displayed inside the graph

enter image description here

2 个答案:

答案 0 :(得分:1)

这个答案是正确的,但是在app.component.ts中,您必须导入chartjs-plugin-datalabels

像这样: 从'chartjs-plugin-datalabels'导入*作为ChartDataLabels;

不是这样的: 从“ chartjs-plugin-datalabels”导入ChartDataLabels;

非常感谢Alexey.S!

答案 1 :(得分:0)

太晚了,我想您已经找到了答案,但是对于将来的人们,可以通过以下方式实现:

  1. 安装插件: npm install chartjs-plugin-datalabels --save
  2. 这将是全局注册的,因此我们需要取消注册,以便仅包括某些图表;例如将其放置在根组件的init方法中

     import * as Chart from 'chart.js';
     import ChartDataLabels from 'chartjs-plugin-datalabels';
     ...
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.scss']
    })
    
    export class AppComponent implements OnInit {
       chartJs = Chart;
       chartLabelPlugin = ChartDataLabels;
    
       constructor() {
       }
    
       ngOnInit(): void {
         this.chartJs.plugins.unregister(this.chartLabelPlugin);
      }
    }
    
  3. 为某些图表添加插件

    import ChartDataLabels from 'chartjs-plugin-datalabels';
    ...
    
    plugin = ChartDataLabels; 
    options = {
      plugins: {
       datalabels: {
         /* show value in percents */
         formatter: (value, ctx) => {
           let sum = 0;
           const dataArr = ctx.chart.data.datasets[0].data;
           dataArr.map(data => {
                 sum += data;
           });
           const percentage = (value * 100 / sum); 
           return percentage !== 0 ? percentage.toFixed(2) + '%' : '';
         },
         color: '#fff',
       }
      }
    }
    
    
    
    <-- html -->
    
     <p-chart [options]="options" 
              [data]="dataset" 
              [plugins]="plugin" 
              type="pie">
     </p-chart>
    
    <-- html -->