Chart.js plugin to display labels on data elements

Overview

Downloads Builds Coverage Awesome

Overview

Highly customizable Chart.js plugin that displays labels on data for any type of charts.

Requires Chart.js 3.x.

Documentation

Development

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

> npm install

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

> npm run build            // build dist files
> npm run build:dev        // build and watch for changes
> npm run test             // run all tests and generate code coverage
> npm run test:dev         // run all tests and watch for changes
> npm run lint             // perform code linting
> npm run lint -- --fix    // automatically fix linting problems
> npm run docs             // generate documentation (`dist/docs`)
> npm run docs:dev         // generate documentation and watch for changes

License

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

Comments
  • Import error:

    Import error: "Module 'chartjs-plugin-datalabels/types/index' has no default export."

    Trying out Chart.js, and have been told I need to use the chartjs-plugin-datalabels to be able to write the percentage text on the piew pieces.

    I installed and imported the chartjs-plugin-datalabels as per the documentation into my Angular 7 project (actually Ionic 4, which uses Angular 7), but vscode reports the following error on the import...

    Module '"../../../../node_modules/chartjs-plugin-datalabels/types"' has no exported member 'ChartDataLabels'.ts(2

    I have the following versions "chart.js": "^2.8.0", "chartjs-plugin-datalabels": "^0.6.0",

    If I go to the node_modules\chartjs-plugin-datalabels\types\index.d.ts file, I also see a similar error here for the line

    declare module 'chart.js

    Invalid module name in augmentation. Module 'chart.js' resolves to an untyped module at 'd:/dev/ionic/chartjstest/node_modules/chart.js/dist/Chart.js', which cannot be augmented.ts

    If I proceed, and try to run, I then get the compile error

    [ng] ERROR in node_modules/chartjs-plugin-datalabels/types/index.d.ts(5,16): error TS2665: Invalid module name in augmentation. Module 'chart.js' resolves to an untyped module at 'D:/dev/ionic/chartjstest/node_modules/chart.js/dist/Chart.js', which cannot be augmented. [ng] src/app/home/pie-graph/pie-graph.component.ts(3,10): error TS2305: Module '"D:/dev/ionic/chartjstest/node_modules/chartjs-plugin-datalabels/types/index"' has no exported member 'ChartDataLabels'.

    bug resolved 
    opened by pjc2007 27
  • Plugin behaviour should be Opt-in, not Opt-out

    Plugin behaviour should be Opt-in, not Opt-out

    First of all thanks for your work on this plugin, much appreciated.

    Right now, when adding the script to page or importing it, it automatically add itself to all charts, which is quite a big assumption on how it's to be used and requires a lot of work to disable it on instance to instance basis.

    enhancement resolved 
    opened by sect2k 22
  • hover.animationDuration:0 doesn't disable animation tooltip with datalabels plugins

    hover.animationDuration:0 doesn't disable animation tooltip with datalabels plugins

    When I use datalabels plugins with options.hover.animationDuration:0 (to disable animation with tooltip), the animation is not disable. If I remove the plugin Datalables (by removing chartjs-plugin-datalabels.js), the animation of tooltip is properly disable.

    Test case : https://jsfiddle.net/dutrieux/w2vzeo3b/ Video for demo : https://youtu.be/Pd293lqSpK8

    bug resolved 
    opened by dutrieux 19
  • Fix declare module Chart

    Fix declare module Chart

    In the declaration of the Chart module to access the datalabels interfaces, it was being created in the wrong way, which was causing problems when executing the code after installing this api.

    I corrected the statement and made the amount correctly.

    needs test case 
    opened by PopyDeveloper 17
  • Font Awesome icons not rendering

    Font Awesome icons not rendering

    I'm trying to show font awesome (4.7) icons as data labels, which seems like it should work because other unicode characters in other font families seem to work ok. Is there something else I should be doing besides the following?

    this.options = {
        plugins: {
            datalabels: {
                color: 'white',
                display: context => {
                    return context.dataset.data[context.dataIndex] > 15;
                },
                font: {
                    weight: 'bold',
                    family: 'FontAwesome',
                    style: 'normal'
                },
                formatter: (value, context) => {
                    return `\\u${context.dataset.icon_code}`;
                }
            }
        },
        ...
    }
    
    support resolved 
    opened by ericsvendsen 16
  • Display one label of the sum of stacked bars

    Display one label of the sum of stacked bars

    Hi,

    I have a horizontal stacked bar chart which looks like this:

    chrome_2017-11-30_14-51-19

    And I would like to display the sum of each stacked bar, like so:

    chrome_2017-11-30_14-50-04

    I managed to get this result by returning an empty string for datasets that are not the last one (datasetIndex), and computing the sum for each bar (dataIndex):

    plugins: {
    	datalabels: {
    		formatter: (value, ctx) => {
    			let datasets = ctx.chart.data.datasets; // Tried `.filter(ds => !ds._meta.hidden);` without success
    			if (ctx.datasetIndex === datasets.length - 1) {
    				let sum = 0;
    				datasets.map(dataset => {
    					sum += dataset.data[ctx.dataIndex];
    				});
    				return sum.toLocaleString(/* ... */);
    			}
    			else {
    				return '';
    			}
    
    		},
    		anchor: 'end',
    		align: 'end'
    	}
    }
    

    It works great, but if I toggle off one dataset (via the chart's legend), the result is less great:

    • if I toggle off the first dataset, I still have the sum of the two datasets as a label:

      chrome_2017-11-30_15-57-51

    • if I toggle off the last dataset, I don't have a label anymore:

      chrome_2017-11-30_15-59-59

    As I commented in my code snippet, I tried to filter out the datasets with the _meta.hidden metadata, but it seems that the formatter function is not called again when toggleing datasets via the chart's legend.

    Is there a better way to use datalabels with stacked bar charts? Or does anyone have an idea to make it work?

    support resolved 
    opened by LeoDupont 16
  • Adding multiple datalabels types on chart

    Adding multiple datalabels types on chart

    Hello ! I was wondering if it was possible to use different datalabels types on a graph. Here is what I currently have : sans titre 1 I am adding the black datalabels with the plugin but didn't find a way to display my blue datalabels by also using the plugin so I'm currently using onComplete from chart.js which is not optimal at all.

    If a similar feature or workaround is not already available, it would be great to be able to do something like this :

    datalabels: [{ // datalabelsType1 },{ // datalabelsType2 }]

    enhancement resolved 
    opened by Lenophie 14
  • [Feature] Is it possible to use images on labels?

    [Feature] Is it possible to use images on labels?

    In the following example I can see it's possible to use carets as font icons. image Source: https://chartjs-plugin-datalabels.netlify.com/samples/scriptable/data.html

    Is it possible to use bitmap or SVG images also?

    wontfix 
    opened by ed1nh0 13
  • Gradient not applied

    Gradient not applied

    I'm trying to apply a gradient as background color to labels but it doesn't work.

    Here is code, based on data labels sample:

    <script id="script-init">
    var ctx = document.getElementById('chart-0').getContext("2d");
    var gradientStroke = ctx.createLinearGradient(500, 0, 100, 0);
    gradientStroke.addColorStop(0, "#80b6f4");
    gradientStroke.addColorStop(1, "#f49080");
    
    	var DATA_COUNT = 8;
    	var labels = [];
    	Samples.srand(8);
    
    	for (var i = 0; i < DATA_COUNT; ++i) {
    		labels.push('' + i);
    	}
    
    	Chart.helpers.merge(Chart.defaults.global, {
    		aspectRatio: 4/3,
    		tooltips: false,
    		layout: {
    			padding: {
    				top: 42,
    				right: 16,
    				bottom: 32,
    				left: 8
    			}
    		},
    		elements: {
    			line: {
    				fill: false
    			}
    		},
    		plugins: {
    			legend: false,
    			title: false
    		}
    	});
    </script>
    
    <script id="script-construct">
    var chart = new Chart('chart-0', {
    	type: 'line',
    	data: {
    		labels: labels,
    		datasets: [{
    			backgroundColor: gradientStroke,
    			borderColor: gradientStroke,
    			data: Samples.numbers({
    				count: DATA_COUNT,
    				min: 0,
    				max: 100
    			})
    		}]
    	},
    	options: {
    		plugins: {
    			datalabels: {
    					backgroundColor: function(context) {
    						return gradientStroke;
    					},
    					borderRadius: 4,
    					color: 'white',
    					font: {
    						weight: 'bold'
    					},
    					formatter: Math.round
    				}
    			},
    			scales: {
    				yAxes: [{
    					stacked: true
    				}]
    			}
    		}
    	});
    </script>
    

    Here is the result:

    canvas

    There is a similar issue in Chart.js, fixed in the master .

    enhancement 
    opened by stockiNail 12
  • Showing/Hiding Based on Visibility of Lines in Chart

    Showing/Hiding Based on Visibility of Lines in Chart

    I have a line chart with a legend and 3 lines drawn. When you click the legend the lines show/hide and the graph adjusts accordingly. Out of the box the datalabels do not hide whenever a line is hidden. I am currently using this method of hiding the datalabels:

    options: {
        plugins: {
            datalabels: {
                display: (context: any) => {
                    return !context.dataset._meta[0].hidden;
                },
            },
        },
    },
    

    This works, but the _meta[0].hidden thing seems like a hack/not something we're supposed to be using. Is there a different approach that is more stable?

    bug resolved 
    opened by wjohnsto 12
  • `gulp build` fails with an error

    `gulp build` fails with an error

    GULP fails to build.

    I installed GULP through npm install gulp in the root directory.

    Windows 10 64-bit:

    • Node.js version: v6.11.1
    • NPM version: 3.10.10
    • GULP CLI & Local versions: 3.9.1

    When I type gulp build in the root directory, I get:

    C:\GIT\chartjs-plugin-datalabels>gulp build
    module.js:471
        throw err;
        ^
    
    Error: Cannot find module 'yargs'
        at Function.Module._resolveFilename (module.js:469:15)
        at Function.Module._load (module.js:417:25)
        at Module.require (module.js:497:17)
        at require (internal/module.js:20:19)
        at Object.<anonymous> (C:\GIT\chartjs-plugin-datalabels\gulpfile.js:3:28)
        at Module._compile (module.js:570:32)
        at Object.Module._extensions..js (module.js:579:10)
        at Module.load (module.js:487:32)
        at tryModuleLoad (module.js:446:12)
        at Function.Module._load (module.js:438:3)
    

    I was hoping to get it as Chart.js pie or bar fail to draw labels inside or outside (I want their percent values displayed so I can print them) but it looks as if that plugin is not supported any longer.

    support resolved 
    opened by hlide 11
  • Labels disappear after chart update

    Labels disappear after chart update

    Current behaviour

    If only active points labels are displayed (display: (context) => context.active) and chart.update() triggered while some labels are displayed, these labels disappear until another point become active.

    Expected behaviour

    chart.update() don't breaks active points label visibility.

    Steps to Reproduce

    1. Open example (https://codesandbox.io/s/plugin-example-forked-7ntsoq?file=/src/App.vue)
    2. Hover on any point
    3. Wait until chart.update() trigger (5 sec)
    4. Labels disappear and appear again only after another point hovered

    Environment

    chart.js: 4.1.1 chartjs-plugin-datalabels: 2.2.0

    opened by Odrin 0
  • TypeScript Compile Error for Mixed Chart Type

    TypeScript Compile Error for Mixed Chart Type

    Issue

    I'm unable to get the below TypeScript to compile due to a type error when using a mixed chart type. According to the Chart.js documentation the type property is set on each dataset when creating a mixed chart (not outside of it like all other charts). The chartjs-plugin-datalabels documentation states that the plugin options can be set per data level so I'm unsure as to why this error is happening. Any insight is appreciated. Thank you!

    import { Chart } from "chart.js/auto";
    import ChartDataLabels from "chartjs-plugin-datalabels";
    
    const chart = new Chart(<HTMLCanvasElement>document.getElementById("mixed"), {
      plugins: [ChartDataLabels],
      data: {
        datasets: [
          {
            // Change options only for labels of THIS DATASET
            datalabels: {         // <-- these three lines cause the error
              color: "#FFCE56",   //
            },                    //
            type: "bubble",
            label: "Bar Dataset",
            data: [
              // 10, 20, 30, 40,
              { x: 15, y: 20, r: 10 },
              { x: 25, y: 10, r: 20 },
            ],
          },
          {
            type: "line",
            label: "Line Dataset",
            data: [
              { x: 10, y: 10 },
              { x: 20, y: 20 },
              { x: 30, y: 30 },
            ],
          },
        ],
      },
    });
    

    Here is the full error:

    [tsl] ERROR in /home/isaac/typescript/my-project/src/index.ts(10,9)
          TS2345: Argument of type '{ plugins: Plugin<keyof ChartTypeRegistry, AnyObject>[]; data: { datasets: ({ datalabels: { color: string; }; type: "bubble"; label: string; data: { x: number; y: number; r: number; }[]; } | { ...; })[]; }; }' is not assignable to parameter of type 'ChartConfiguration<keyof ChartTypeRegistry, { x: number; y: number; r: number; }[] | { x: number; y: number; }[], unknown> | ChartConfigurationCustomTypesPerDataset<keyof ChartTypeRegistry, { ...; }[] | { ...; }[], unknown>'.
      Type '{ plugins: Plugin<keyof ChartTypeRegistry, AnyObject>[]; data: { datasets: ({ datalabels: { color: string; }; type: "bubble"; label: string; data: { x: number; y: number; r: number; }[]; } | { ...; })[]; }; }' is not assignable to type 'ChartConfigurationCustomTypesPerDataset<keyof ChartTypeRegistry, { x: number; y: number; r: number; }[] | { x: number; y: number; }[], unknown>'.
        The types of 'data.datasets' are incompatible between these types.
          Type '({ datalabels: { color: string; }; type: "bubble"; label: string; data: { x: number; y: number; r: number; }[]; } | { type: "line"; label: string; data: { x: number; y: number; }[]; })[]' is not assignable to type 'ChartDatasetCustomTypesPerDataset<keyof ChartTypeRegistry, { x: number; y: number; r: number; }[] | { x: number; y: number; }[]>[]'.
            Type '{ datalabels: { color: string; }; type: "bubble"; label: string; data: { x: number; y: number; r: number; }[]; } | { type: "line"; label: string; data: { x: number; y: number; }[]; }' is not assignable to type 'ChartDatasetCustomTypesPerDataset<keyof ChartTypeRegistry, { x: number; y: number; r: number; }[] | { x: number; y: number; }[]>'.
              Type '{ datalabels: { color: string; }; type: "bubble"; label: string; data: { x: number; y: number; r: number; }[]; }' is not assignable to type 'ChartDatasetCustomTypesPerDataset<keyof ChartTypeRegistry, { x: number; y: number; r: number; }[] | { x: number; y: number; }[]>'.
                Object literal may only specify known properties, and 'datalabels' does not exist in type '_DeepPartialObject<{ type: "bubble"; } & BubbleControllerDatasetOptions> & ChartDatasetPropertiesCustomTypesPerDataset<keyof ChartTypeRegistry, { ...; }[] | { ...; }[]>'.
    

    Environment Info

    I'm using VS Code for editing and Webpack when compiling.

    Chart.js: 4.0.1 chartjs-plugin-datalabels: 2.2.0

    TypeScript: 4.9.4 tsconfig.json

    {
      "compilerOptions": {
        "outDir": "./dist/",
        "noImplicitAny": true,
        "target": "es5",
        "module": "es6",
        "allowJs": true,
        "jsx": "react",
        "moduleResolution": "node",
        "sourceMap": true
      }
    }
    

    webpack.config.js

    const path = require("path");
    
    module.exports = {
      entry: "./src/index.ts",
      devtool: "inline-source-map",
      module: {
        rules: [
          {
            test: /\.tsx?$/,
            use: "ts-loader",
            exclude: /node_modules/,
          },
        ],
      },
      resolve: {
        extensions: [".tsx", ".ts", ".js"],
      },
      output: {
        filename: "bundle.js",
        path: path.resolve(__dirname, "dist"),
      },
    };
    
    opened by isaacsando 2
  • I Need datalabels(stacked bar) on top up label annotation (image and  text)

    I Need datalabels(stacked bar) on top up label annotation (image and text)

    Hey

    I'm trying to make these data labels(stacked bar) with label annotation (image and text) please check the below image image

    please give me any suggestions for this problem

    this is codesandbox link https://codesandbox.io/s/optimistic-curie-bxwh5t

    opened by JogaraoBurakayala 0
  • Handling overlapping labels

    Handling overlapping labels

    Hello! I'm using this plugin to show data labels on a scatter graph.

    Here is a fully working example on Codepen: https://codepen.io/LondonAppDev/pen/oNyReVr

    I want to implement a "bring to the front" effect of labels when you hover over them. So all labels are visible and overlap, but when I hover over a point/label it is brought to the foreground.

    After reading the docs, I see that the order is determined using the dataIndex and then datasetIndex, so I tried to implement it by adding the following to options.plugins.datalabels.labels.value:

        listeners: {
            enter: function(context) {
              context.dataIndex = 999;
              context.datasetIndex = 999;
              return true;
            },
            leave: function(context) {
              context.dataIndex = 0;
              context.datasetIndex = 0;
              return true;
            }
          }
    

    This unfortunately doesn't work, it just seems to crash when I hover.

    Does anyone know if this is possible to achieve?

    opened by LondonAppDev 0
  • Critical: Cannot read properties of undefined (reading '_labels') <> Angular 12

    Critical: Cannot read properties of undefined (reading '_labels') <> Angular 12

    Here are my chart.js versions:

    Error: Cannot read properties of undefined (reading '_labels')

    Problem statement:

    I can't produce the workflow or step-by-step why it creates an issue. I make sure labels are assigned before I load a chart.

    Still doesn't understand the exact cause of the issue.

    Versions:

     "chart.js": "3.7.0",
      "chartjs-plugin-datalabels": "2.0.0",
    
    

    The full error:

    core.js:7744 ERROR TypeError: Cannot read properties of undefined (reading '_labels')
        at Object.afterDatasetsDraw (chartjs-plugin-datalabels.esm.js:1304:43)
        at callback (helpers.segment.js:92:15)
        at PluginService._notify (chart.esm.js:4922:19)
        at PluginService.notify (chart.esm.js:4909:25)
        at Chart.notifyPlugins (chart.esm.js:6047:26)
        at Chart._drawDatasets (chart.esm.js:5797:10)
        at Chart.draw (chart.esm.js:5768:10)
        at chart.esm.js:64:15
        at Map.forEach (<anonymous>)
        at Animator._update (chart.esm.js:42:18)
    

    Is there anything else I should provide to find the issue? I appreciate any help, as it is impacting our production environment charts.

    needs test case 
    opened by vatsal2210 1
Releases(v2.2.0)
Owner
Chart.js
Simple, clean and engaging charts for designers and developers
Chart.js
Chart.js plugin to defer initial chart updates

Chart.js plugin to defer initial chart updates until the user scrolls and the canvas appears inside the viewport, and thus trigger the initial chart a

Chart.js 97 Nov 9, 2022
A Simple Dashboard Chart in Laravel Nova using Chart JS

A Simple Dashboard Chart in Laravel Nova using Chart JS. Starting create your own dashboard with Chart JS Integration can save your time and help you maintain consistency across standard elements such as Bar, Stacked, Line, Area, Doughnut and Pie Chart.

Kuncoro Wicaksono 177 Jan 4, 2023
Bar Funnel Chart extension for Chart.js

Chart.BarFunnel.js Provides a Bar Funnel Chart for use with Chart.js Documentation To create a Bar Funnel Chart, include Chart.BarFunnel.js after Char

Chart.js 58 Nov 24, 2022
TradeX-chart is a trade chart written in plain (vanilla) JavaScript with minimal dependencies

TradeX-chart is a trade chart written in plain (vanilla) JavaScript with minimal dependencies; use it with any framework or backend.

null 24 Dec 12, 2022
API to generate candlestick chart data for any time period based on transactions data

candel-maker API to generate candlestick chart data for any time period based on transactions data Installation clone repo git clone https://github.co

null 2 Aug 18, 2022
Chart.js plugin for live streaming data

chartjs-plugin-streaming Chart.js plugin for live streaming data chartjs-plugin-streaming 2.x requires Chart.js 3.0.0 or later. If you need Chart.js 2

Akihiko Kusanagi 401 Dec 27, 2022
Draggable data points plugin for Chart.js

chartjs-plugin-dragdata.js Now compatible with Chart.js v3 ?? Looking for a version compatible to Chart.js < 2.9.x? Then visit the v2 branch! A plugin

Christoph Pahmeyer 196 Dec 18, 2022
Chart.js plugin for Prometheus data loading

Welcome to chartjs-plugin-datasource-prometheus ?? A Prometheus datasource for ChartJS. Dependencies: requires chart.js 2.7 or later. requires moment.

Samuel Berthe 77 Dec 6, 2022
🍞📊 Beautiful chart for data visualization.

?? ?? Spread your data on TOAST UI Chart. TOAST UI Chart is Beautiful Statistical Data Visualization library. ?? Packages The functionality of TOAST U

NHN 5.2k Jan 2, 2023
🍞📊 Beautiful chart for data visualization.

?? ?? Spread your data on TOAST UI Chart. TOAST UI Chart is Beautiful Statistical Data Visualization library. ?? Packages The functionality of TOAST U

NHN 5.2k Jan 6, 2023
Chart.js scale for hierarchical tree-like data structure

Chart.js Hierarchical Scale Plugin Chart.js module for adding a new categorical scale which mimics a hierarchical tree. Related Plugins Check out also

Samuel Gratzl 40 Dec 17, 2022
Timeline/Graph2D is an interactive visualization chart to visualize data in time.

vis-timeline The Timeline/Graph2D is an interactive visualization chart to visualize data in time. The data items can take place on a single date, or

vis.js 1.2k Jan 3, 2023
Zoom and pan plugin for Chart.js

chartjs-plugin-zoom A zoom and pan plugin for Chart.js >= 3.0.0 For Chart.js 2.6.0 to 2.9.x support, use version 0.7.7 of this plugin. Panning can be

Chart.js 510 Jan 2, 2023
Chart.js plugin for more styling options

chartjs-plugin-style Chart.js plugin for more styling options This plugin requires Chart.js 2.6.0 or later. Installation You can download the latest v

Akihiko Kusanagi 57 Oct 27, 2022
Chart.js plugin to create charts with a hand-drawn, sketchy, appearance

chartjs-plugin-rough Chart.js plugin to create charts with a hand-drawn, sketchy, appearance Version 0.2 requires Chart.js 2.7.0 or later, and Rough.j

Akihiko Kusanagi 73 Dec 1, 2022
Chart.js plugin to calculate and draw statistical linear, exponential, power, logarithmic, and polynomial regressions.

chartjs-plugin-regression Chart.js plugin to calculate and draw statistical linear, exponential, power, logarithmic, and polynomial regressions using

Wilfredo Pomier 14 Dec 18, 2022
Annotation plugin for Chart.js

chartjs-plugin-annotation.js An annotation plugin for Chart.js >= 3.0.0 This plugin needs to be registered. It does not function as inline plugin. For

Chart.js 515 Dec 30, 2022
Make Your Company Data Driven. Connect to any data source, easily visualize, dashboard and share your data.

Redash is designed to enable anyone, regardless of the level of technical sophistication, to harness the power of data big and small. SQL users levera

Redash 22.4k Dec 30, 2022
Github action generates dynamic image URL for contributor list to display it!

github-action-contributors Github action generates dynamic image URL for contributor list to display it! Contributors Usage - run: mkdir -p build - na

小弟调调™ 10 Dec 31, 2022