score:0

import { charttype, chartoptions } from 'chart.js';
import { multidataset, label, pluginserviceglobalregistrationandoptions } from 'ng2-charts';

that: this;
invalue: string = 'text you need to add in dynamicly';

  public doughnutchartlabels: label[] = [];
  public doughnutchartdata: multidataset = [];
  public doughnutchartplugins: pluginserviceglobalregistrationandoptions[]=[{}];
  public doughnutcharttype: charttype = 'doughnut';
  public config: chartoptions = {
    responsive: true,
    maintainaspectratio: false,
    legend: {
      position: 'bottom'
    },
    tooltips: {
      enabled: false
    },
    rotation: 0,
    cutoutpercentage: 65
  };
  colors = [
    {
      backgroundcolor: [
        '#63ba68',
        '#eae9e9'
      ],
      borderwidth: 0
    }
  ];
  ngoninit(): void {
    this.doughnutchartdata.push([[[your data]]]);
  }

  ngafterviewinit(): void {
    this.that = this;
    this.doughnutchartplugins= [this.returnobjectdoughnutchartplugins(this.that)]
  }

  returnobjectdoughnutchartplugins(that: this) {
    return {
      beforedraw(chart) {
        const ctx = chart.ctx;
        const txt: string = that.invalue;
        ctx.textalign = 'center';
        ctx.textbaseline = 'middle';
        const centerx = ((chart.chartarea.left + chart.chartarea.right) / 2);
        const centery = ((chart.chartarea.top + chart.chartarea.bottom) / 2);
        const fontsizetouse = 22;
        ctx.font = `${fontsizetouse}px yourfont`;
        ctx.fillstyle = '#444444';
        ctx.filltext(txt, centerx, centery);
        ctx.shadowcolor = '#767676';
        ctx.shadowblur = 0.5;
        ctx.shadowoffsetx = 0.1;
        ctx.shadowoffsety = 1;
      }
    }
  }
}

score:6

you can do the following to place text in the center of doughnut chart. it worked for me

html:

 <div style="display: block">
  <canvas #mycanvas basechart 
              [data]="doughnutchartdata"
              [labels]="doughnutchartlabels"
              [charttype]="doughnutcharttype"
              (charthover)="charthovered($event)"
              (chartclick)="chartclicked($event)"></canvas>
</div>

typescript

import {component, ngmodule, elementref, inject, viewchild} from '@angular/core'
import {browsermodule} from '@angular/platform-browser'
import {chartsmodule, color} from 'ng2-charts';

export class app{
   @viewchild('mycanvas')
  canvas:elementref; 

 ngoninit(){
    var ctx = this.canvas.nativeelement.getcontext("2d");

    let me = this;
    this.options = {

      circumference: math.pi,
      rotation :  math.pi,
      animation:{ oncomplete: function() {
         me.doit(ctx);
       }}
    }

      }

     doit(ctx) {
         //   chart.types.doughnut.prototype.draw.apply(this, arguments);

            var width = this.canvas.nativeelement.clientwidth,
                height = this.canvas.nativeelement.clientheight;

            var fontsize = (height / 250).tofixed(2);
            ctx.font = fontsize + "em verdana";
            ctx.textbaseline = "middle";
            ctx.fillstyle = "blue";

            var text = "pass rate 82%",
                textx = math.round((width - ctx.measuretext(text).width) / 2),
                texty = height -10;

            ctx.filltext(text, textx, texty);
            ctx.restore();
        }
}
}

score:7

you can place both label and its value in center of doughnut.

when you hover it hover value will be updated in the center of chart.

import { component, oninit } from '@angular/core';
import { charttype } from 'chart.js';
import { singledataset, label, pluginserviceglobalregistrationandoptions } from 'ng2-charts';

@component({
  selector: 'my-app',
  templateurl: './app.component.html',
  styleurls: ['./app.component.css']
})
export class appcomponent {
  // doughnut
  public doughnutchartlabels = ['download sales', 'in-store sales'];
  public doughnutchartdata: singledataset = [
    [350, 450]
  ];
  public doughnutcharttype: charttype = 'doughnut';
  public doughnutchartplugins: pluginserviceglobalregistrationandoptions[] = [{
    afterdraw(chart) {
      const ctx = chart.ctx;
      var txt1 = '';
      var txt2 = '';    

      try{
        var check = chart.active ? chart.tooltip._active[0]._datasetindex : "none";
        if(check !== "none"){
        txt1 = chart.tooltip._data.labels[chart.tooltip._active[0]._index];
        txt2 = chart.tooltip._data.datasets[0].data[chart.tooltip._active[0]._index];        
      }else{
        txt1 = chart.tooltip._data.labels[0];
        txt2 = chart.tooltip._data.datasets[0].data[0];
      }
      }
      catch(err){
        txt1 = chart.tooltip._data.labels[0] 
        txt2 = chart.tooltip._data.datasets[0].data[0];
      }
      //get options from the center object in options
      const sidepadding = 60;
      const sidepaddingcalculated = (sidepadding / 100) * (chart.innerradius * 2)

      ctx.textalign = 'center';
      ctx.textbaseline = 'middle';
      const centerx = ((chart.chartarea.left + chart.chartarea.right) / 2);
      const centery = ((chart.chartarea.top + chart.chartarea.bottom) / 2);

      //get the width of the string and also the width of the element minus 10 to give it 5px side padding

      const stringwidth = ctx.measuretext(txt1).width;
      const elementwidth = (chart.innerradius * 2) - sidepaddingcalculated;

      // find out how much the font can grow in width.
      const widthratio = elementwidth / stringwidth;
      const newfontsize = math.floor(30 * widthratio);
      const elementheight = (chart.innerradius * 2);

      // pick a new font size so it will not be larger than the height of label.
      const fontsizetouse = 30;
      ctx.font = fontsizetouse + 'px arial';
      ctx.fillstyle = 'black';

      // draw text in center
      ctx.filltext(txt2, centerx, centery - 10);
      var fontsizetouse1 = 15;
      ctx.font = fontsizetouse1 + 'px arial';
      ctx.filltext(txt1, centerx, centery + 10);
    }
  }];

  constructor() { }

  ngoninit() {
  }

  // events
  public chartclicked({ event, active }: { event: mouseevent, active: {}[] }): void {
    //console.log(event, active);
  }

  public charthovered({ event, active }: { event: mouseevent, active: {}[] }): void {
    //console.log(event, active);
  }
}

html

<div>
  <div>
    <div style="display: block">
      <canvas basechart [data]="doughnutchartdata" [labels]="doughnutchartlabels" [charttype]="doughnutcharttype"
        [plugins]="doughnutchartplugins" (charthover)="charthovered($event)"
        (chartclick)="chartclicked($event)"></canvas>
    </div>
  </div>
</div>

enter image description here

happy coding :)


Related Query

More Query from same tag