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>
Happy Coding :)
Source: stackoverflow.com
Related Query
- Vue Chart 3 - Doughnut Charts with Text in the Middle (Trouble registering a plugin)
- Angular 2 ng2-charts doughnut text in the middle disappears on mouse hover
- Angular 2 ng2-charts doughnut text in the middle?
- How can I add some text in the middle of a half doughnut chart in Chart.JS?
- How to rotate the Label text in doughnut chart slice vertically in chart.js canvas, Angular 12?
- Styling the middle text of Chart.js's doughnut chart
- The dataset for bar graph is not set properly using ng2 charts and ng5-slider in Angular
- How to add text inside the doughnut chart using Chart.js?
- How to add text in centre of the doughnut chart using Chart.js?
- How to display the labels in doughnut chart using ng2 charts?
- Chart.js - How to Add Text in the Middle of the Chart?
- Multipe doughnut charts on one page with text in center using Chart.js
- How to add text inside the doughnut chart using Chart.js version 3.2.1
- Chart.js - Fill Text only appearing when hovering over one part of the doughnut
- How to change the color of the bar in barchart if the data is negative - Angular Charts
- How to add text inside the doughnut chart using Chart.js AngularJS 2.0?
- ng2 charts bar chart need spacing between 2 bars in series Angular
- Hide the element text on line charts since it overlaps with the line
- Chart.js: Thousand Separator and Tittle ind the Middle of the Doughnut
- how to see labels without losing middle text in doughnut chart
- The dataset in ng2 charts for bar graph is not setting properly
- Angular 8 and ng2 charts - Updating labels and data
- While placing chart.js Doughnut Chart inside Primeng Carousel, the text inside the canvas seems blurred/distorted a little bit
- ng2 charts on Angular 9 not responsive
- How to vary the thickness of doughnut chart, using ChartJs.?
- Chart.js Doughnut with rounded edges and text centered
- Chart.js v2 charts do not display inside angular 2 (but Chart.js v1 works perfectly)
- ChartJS Doughnut Charts Gradient Fill
- line graph spot in the top middle of the bar graph
- Chart js. How to align text by the center of the tooltip?
More Query from same tag
- How to start the line graph from the left Y axis in a line/bar mixed chart (Chart.js)?
- Date selection not happening with a click in chartjs in the context of vuejs
- White space at start and end of data with time scale in chart.js
- chartjs x-axis category label (with data from tabletop.js)
- Chart js: generate dynamic labels according to the data
- How to display data on hover inside doughnut chart in Angular Chart?
- Inner Radius is not changed in Chart.js (Doughnut Chart)
- Vue grouping items by key then charting similar keys in one chart
- How to call a function when an element is loaded in Angular?
- How can I make two of my lines in Chart JS thicker
- Chart.js Treemap Adding custom text to each rectangle
- How to display the more then one value inside tooltip in bar chart.js?
- ChartJS: Show all tooltips with Total for Multi Pie chart
- How to install Chart.js in Laravel?
- Charts.js tooltip overlapping text on chart
- Bar color in ChartJS not updating
- Need help splitting date to new line in Doughnut Chart js
- Is there any way to show a tooltip for points which are not visible on the chart in Chart.js?
- How to set default callback for tooltip title with chart.js
- How to add Chart.js to Wagtail Homepage panels using construct_homepage_panels hook?
- Chart options not used with chart js
- Chart.js - generateLegend() call results in "undefined is not a function"
- Type error in using chartjs and tc-angular-chartjs
- Chart.js - How to Add Text in the label of the Chart with JavaScript?
- Piechart doesn't show up in Canvas
- ChartJS 2.6 - Bar chart fixed height scrollable-X
- ChartJS linechart edit yAxis labels
- Chart.js - get x-axis label (or index) in onHover event
- Could not find elementById on mat-card-content
- How to format tool tip as currency in piechart chartJS?