You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过JavaScript或Angular在PrimeNG饼图内显示数值?

How to Display Values (Including Negatives) Inside PrimeNG Pie Chart Slices

Got it, let's get those values (even negative ones like -50) showing right inside your PrimeNG pie chart slices! Since PrimeNG's <p-chart> is built on top of Chart.js, we can use Chart.js's official plugins and configuration to make this happen easily.

Step 1: Install the Chart.js Data Labels Plugin

First, we need the chartjs-plugin-datalabels plugin—it's the simplest way to add internal labels to chart elements. Install it via npm:

npm install chartjs-plugin-datalabels --save

Step 2: Update Your Component Code

Modify your app.component.ts to register the plugin, set up the chart options for labels, and include negative values in your dataset:

import { Component } from '@angular/core';
import ChartDataLabels from 'chartjs-plugin-datalabels';
import { Chart } from 'chart.js';

export class PieChartDemo {
  data: any;
  chartOptions: any;

  constructor() {
    // Register the data labels plugin globally
    Chart.register(ChartDataLabels);

    this.data = {
      labels: ['A', 'B', 'C'],
      datasets: [{
        data: [300, -50, 100], // Example with positive and negative values
        backgroundColor: ["#FF6384", "#36A2EB", "#FFCE56"],
        hoverBackgroundColor: ["#FF6384", "#36A2EB", "#FFCE56"]
      }]
    };

    this.chartOptions = {
      plugins: {
        datalabels: {
          color: '#ffffff', // White text for contrast against slice colors
          font: {
            weight: 'bold',
            size: 14
          },
          // Format the value to show as-is (including negatives)
          formatter: (value: number) => value.toString(),
          // Position label in the center of each slice
          anchor: 'center',
          align: 'center'
        }
      }
    };
  }
}

Step 3: Update Your Template

Bind the chartOptions to your <p-chart> component in app.component.html:

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

How It Works

  • The chartjs-plugin-datalabels handles rendering the labels directly on each pie slice.
  • The formatter function ensures we display the exact value (positive or negative) without any modifications.
  • The anchor and align settings make sure the label sits perfectly in the center of each slice for readability.

That's it! Your pie chart will now show all values—including negatives—right inside each corresponding slice.

内容的提问来源于stack exchange,提问作者Sudhin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:11:13