Code Monkey home page Code Monkey logo

chartjs-plugin-doughnutlabel's Introduction

Chart.js Doughnut plugin to allow for lines of text in the middle

Chart.js plugin module that allows to display multiple lines of text centered in the middle area of the doughnut charts

Demo

Have a look at the Demo page.

Table of contents

Installation

Install through npm:

npm install --save chartjs-plugin-doughnutlabel

Usage

var myDoughnutChart = new Chart(ctx, {
  type: 'doughnut',
  data: data,
  options: {
    plugins: {
      doughnutlabel: {
        labels: [
          {
            text: 'The title',
            font: {
              size: '60'
            }
          },
          {
            text: getTotal,
            font: {
              size: '50'
            },
            color: 'grey'
          },
          {
            text: '$100.000',
            font: {
              size: '30'
            },
            color: 'red'
          },
          {
            text: '95%',
            font: {
              size: '45'
            },
          color: 'green'
          }
        ]
      }
    }		
  }
});

var getTotal = function(myDoughnutChart) {
	var sum = myDoughnutChart.config.data.datasets[0].data.reduce((a, b) => a + b, 0);
	return `Total: ${sum}`;
}

Usage without a module bundler

The plugin can be manually downloaded from the Releases page on GitHub!

<script src="chartjs-plugin-doughnutlabel.js"></script>

or use the minified version

<script src="chartjs-plugin-doughnutlabel.min.js"></script>

Development

You first need to install node dependencies (requires Node.js):

> npm install

The following commands will then be available from the repository root:

> gulp lint             // perform code linting
> gulp build            // build dist files
> gulp build --watch    // build and watch for changes
> gulp package          // create an archive with dist files and samples

In Angular

For an example on how to use this plugin with angular, please check this stackblitz prototype: doughnutlabel plugin in angular

License

chartjs-plugin-doughnutlabel is available under the MIT license.

chartjs-plugin-doughnutlabel's People

Contributors

ciprianciurea avatar johnarcher avatar jonathancounihan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

chartjs-plugin-doughnutlabel's Issues

[Request] HTML Support in Label

Feature Proposal

Function for add html tags in to center text.

Feature Use Case

This can help add icons, (example: from font awesome) in middle
Also, You can use tags like <strong>, <small> etc.
For example:
image

Possible Implementation

Example:

                plugins: {
                    doughnutlabel: {
                        labels: [
                            {
                                html-text: "<strong>" + Total + "</strong>" + " " + "<small>" + "%" + "</small>"
                            }
                        ]
                    }
                }

Recalculate and update label text

Recalculate and update label text on hover particular doughnut section.
The case is when I roll over particular sector I want some calculated value appear inside chart label.
The default calculated value is the percentage that occupies hovered section against all others.
The label is the dataset label of the selected section.

I am thinking of some callbacks to do this. Is it possible?

Display Total

Is there anyway to display the total rather than just static text. Most doughnut charts that I have seen allow the user to display the total as a value in the center.

Do you accept pull requests as I could do this myself.

unable to sync label in center of donut with caption filtering

I am using ng2-charts with the chartjs-plugin-donut label

my problem is that I cannot update the total in my dougnut label with the filtering offered by charts js

    @Input() set total(total: number) {
        this.totalElements = total;
        this.doughnutChartOptions = {
            devicePixelRatio: 1.5,
            responsive: true,
            layout: {
                padding: {
                    left: 10,
                    right: 10,
                    top: 10,
                    bottom: 10
                }
            },
            legend: {
                position: this.doughnutChartLegendPosition,
                labels: {
                    boxWidth: 20,
                    fontColor: '#141741',
                    fontSize: 10,
                    fontFamily: 'Helvetica, Roboto, Arial, sans-serif'
                }
            },
            animation: {
                animateScale: true,
                animateRotate: true
            },
            plugins: {
                doughnutlabel: {
                    labels: [
                        {
                            text: this.totalElements,
                            font: {
                                size: '60',
                                units: 'em',
                                family: 'Arial, Helvetica, sans-serif',
                                style: 'italic',
                                weight: 'bold'
                            }
                        }
                    ]
                }
            }
        };
    }

Try to install in Angular 6

Hello guys
I'm tried to use the plugin in angular but i can't use the plugin,
i imported this plugin and installed the NPM package module but the dependencie dosen't works
One solution for this problem .

PD: Before the all i work from mexican companie for this mi comentaries are wrote in spanish

import * from 'chartjs-plugin-datalabels';

this is the code in html

`


<canvas #mycanvas baseChart [data]="doughnutChartData" [labels]="doughnutChartLabels" [options]="options"
[chartType]="doughnutChartType" [colors]="color">

`

this is the code in TypeScript

`import { Component, OnInit, Input, QueryList, ViewChildren, ViewChild, ChangeDetectorRef, OnChanges } from '@angular/core';
import { DashboardService } from '../../../../../core/services/dashboard.service';
import { BaseChartDirective, Color } from 'ng2-charts';
import { Chart } from 'chart.js';
import { isString } from '@ng-bootstrap/ng-bootstrap/util/util';

@component({
selector: 'm-pichart-warehouse',
templateUrl: './pichart-warehouse.component.html',
styleUrls: ['./pichart-warehouse.component.scss']
})
export class PichartWarehouseComponent implements OnInit,OnChanges {

//El tipo de grafica que sera 0 = Secos 1 = Frios 2 = Congelados
@input() typeLoad: number;

@ViewChildren(BaseChartDirective) charts: QueryList;
@ViewChild(BaseChartDirective) private _chart;

//Propiedad de donde obtiene la grafica el nombre
public doughnutChartLabels: string[] = ['Vacio'];

//Propiedad donde la grafica obtiene sus datos
public doughnutChartData: any = [0];

//El tipo de grafica que vendra
public doughnutChartType: string = 'doughnut';

//El color de la grafica por defecto si no contiene nada
public color: Color[] = [
{ backgroundColor: ['#578EBE', '#F36A5A', '#F2784B', '#E08283', '#1BBC9B', '#8E44AD', ' #F4D03F', '#E5E5E5'] }
];

//Las opciones que tendra personalizadas la grafica
public options: any = {
showActualPercentages: true,
legend: {position: 'left'},
// Aqui se agrega el label central
elements: {
center: {
text: '' + this.doughnutChartData.reduce((a, b) => a + b, 0) + '%',
color: '#FFFFF',
// fontStyle: 'Arial',
sidePadding: 20
}
},
//Aqui genera el label que se muestra en el mouse hover
tooltips: {
callbacks: {
label: function (tooltipItem, data) {
let allData = data.datasets[tooltipItem.datasetIndex].data;
let tooltipLabel = data.labels[tooltipItem.index];
let tooltipData = allData[tooltipItem.index];
let total = 0;
for (let i in allData) {
total += allData[i];
}
let tooltipPercentage = Math.round((tooltipData / total) * 100);
return tooltipLabel + ': ' + tooltipData + ' (' + tooltipPercentage + '%)';
}
}
}
}

constructor(
private cdr: ChangeDetectorRef,
private Dashboardservice: DashboardService,
) { }

ngOnInit() {
//Este plugin gemera el label del centro
Chart.pluginService.register({
beforeDraw: function (chart) {
if (chart.config.options.elements.center) {
var ctx = chart.chart.ctx;
var centerConfig = chart.config.options.elements.center;
// var fontStyle = centerConfig.fontStyle || 'Arial';
var txt = centerConfig.text;
var color = centerConfig.color || '#000';
var sidePadding = centerConfig.sidePadding || 20;
var sidePaddingCalculated = (sidePadding / 100) * (chart.innerRadius * 2)
ctx.font = "30px ";
// + fontStyle;
var stringWidth = ctx.measureText(txt).width;
var elementWidth = (chart.innerRadius * 2) - sidePaddingCalculated;
var widthRatio = elementWidth / stringWidth;
var newFontSize = Math.floor(30 * widthRatio);
var elementHeight = (chart.innerRadius * 2);
var fontSizeToUse = Math.min(newFontSize, elementHeight);
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
var centerX = ((chart.chartArea.left + chart.chartArea.right) / 2);
var centerY = ((chart.chartArea.top + chart.chartArea.bottom) / 2);
ctx.font = fontSizeToUse + "px ";
// + fontStyle;
ctx.fillStyle = color;
ctx.fillText(txt, centerX, centerY);
}
}
});
}

ngOnChanges(changues) {
this.loadWharehousebyLocation();
}

/**

  • Obitiene los valores del back y los asigna a la grafica que muestra en pantalla
  • @param Time Este parametro dice cual es el rango de fecha se obtendran los datos
    */
    loadWharehousebyLocation(): void {
    this.Dashboardservice.findWarehousebyLocation(this.typeLoad).subscribe(res => {
    if (res.data.Ware.length == 0) {
    this.chargeDefaultToChart();
    } else {
    this.chargeDataToChart(res.data.Ware);
    }
    });
    }

/**

  • Esta funcion carga al char todos los valores del obtenidos
  • @param data.name obtendra los nombres de los clientes
  • @param data.id obtiene la cantidad de registros
    */
    chargeDataToChart(data: any[]): void {
    Object.keys(data).map(i => data[i])
    let client_names: string[] = [], io_values: any[] = [];
    data.forEach(item => {
    client_names.push(item.name);
    if(isString(item.count)){
    io_values.push( Number(item.count) );
    }else{
    io_values.push(item.count);
    }
    });
    this.doughnutChartLabels.length = 0;
    this.doughnutChartLabels.push(...client_names);
    this.doughnutChartData = [];
    this.doughnutChartData = io_values;
    this.cdr.detectChanges();
    this.updateChart();
    }

/**

  • Realiza las funciones necesarias para dar update a las graficas
    */
    updateChart(): void {
    this.options.elements.center.text = "";
    let text =this.generatePercentage(this.doughnutChartData);
    console.log(text);
    this.options.elements.center.text = text;
    this.forceChartRefresh();
    }

/**

  • Hace update forsado a los charts
    */
    forceChartRefresh(): void {
    setTimeout(() => {
    this._chart.refresh();
    }, 10);
    this.charts.forEach((child) => {
    child.chart.update();
    });
    }

/**

  • Carga todos los valores por defecto de la grafica
    */
    chargeDefaultToChart(): void {
    this.doughnutChartLabels = ['Vacio'];
    this.doughnutChartData = [0];
    this.cdr.detectChanges();
    this.options.elements.center.text = "";
    this.options.elements.center.text = "0%";
    this.forceChartRefresh();
    }

/**

  • Obtiene un array para calcular el porcentage de uso
  • @param Values obtiene un array de valrores numericos EJ [2,3,46,7]
    */
    generatePercentage(Values: number[] ): string{
    let total_used = 0;
    for(let i =0;i < Values.length-1;i++ ){
    total_used += Values[i];
    }
    let percentage: number = ((total_used / Values.reduce((a, b) => a + b, 0)) * 100);
    return ""+percentage.toFixed()+"%"
    }
    }`

If can help me with that i appreciated to much that because the plugin this plugin are good

Chart JS Version 3++

Is it possible to support Chart JS version 3++? especially for Chart JS React Component

Help needed to use this plugin

Hi, I installed this plugin using npm and I'm trying to use it with a chart. Now the problem is that when I use the example, the chart disappears. How can I import the plugin type of this lib so I can use it like : "DoughnutLabelPluginTypeExample"

options: {
    plugins: {
      doughnutlabel: {
        labels: []...
        ....
    }
  }
},
plugins:[DoughnutLabelPluginTypeExample]

Different font sizes

Hi,

Is it possible to set a different font config for each line?

I tried:

plugins: {
    doughnutlabel: {
        labels: ['Taux avancement', '95%'],
        fonts: [
            {
                size: '20',
            },
            {
                size: '60',
                weight: 'bold'
            }
        ]
    }
}

But its nor working

[Request] Font Awesome support

Plugin called 60 times

Thanks for an awesome plugin!

I have a strange issue on very basic setup. Plugin called 60 times for some reason.

It happens with every interaction with chart including hover. This slows down chart rendering.

Check out the attached screenshot with word HELLO appeared in debug console 60 times:

Screen Shot 2020-04-30 at 08 44 10

See the code below:

 <canvas id="myChart"></canvas>

<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>

<script src="https://github.com/ciprianciurea/chartjs-plugin-doughnutlabel/releases/download/2.0.3/chartjs-plugin-doughnutlabel.js"></script>


<script>
var ctx = document.getElementById('myChart').getContext('2d');

var myDoughnutChart = new Chart(ctx, {
  type: 'doughnut',
      data: {
        labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
        datasets: [{
            label: 'My First dataset',
            backgroundColor: 'rgb(255, 99, 132)',
            borderColor: 'rgb(255, 99, 132)',
            data: [0, 10, 5, 2, 20, 30, 45]
        }]
    },
  options: {
    plugins: {
      doughnutlabel: {
        labels: [

          {
            text: total,
            font: { size: '50' },
            color: 'gray'
          }

        ]
      }
    }		
  }
});

function total() {
  console.log('HELLO')
  return 'HELLO'
}
</script>

Can you verify if it happens on your side as well?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.