Giter Club home page Giter Club logo

chartjs-plugin-labels's People

Contributors

alonstar avatar asr21 avatar babbiorsetto avatar chriskatsaras avatar christopherwk210 avatar davideviolante avatar eduard-landclan avatar emfhdinf avatar emn178 avatar fwwarr avatar gstark avatar hintalo avatar levy-d avatar seb33300 avatar shripalsoni04 avatar taystack avatar thebrenny avatar yousef337 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

Watchers

 avatar  avatar  avatar  avatar

chartjs-plugin-labels's Issues

Invert arc labels

Hi! Firstly, thank you for taking over this library. It's super useful (and is teaching me a lot about charts, haven't really used them before this).

There is an open pull request (code here) in the unmaintained version of this lib that flips the labels underneath the arcs where the text would otherwise be upside down. However, this code is no longer compatible with the updates you've made to this lib, so it's not easy for me to migrate over.

Please would you consider porting this to allow the text to be flipped at the bottom of the arc? Or is this functionality already in here somewhere?

NaN and overlapping on bar chart

When the value is 0 for some labels.

Screenshot from 2021-07-06 09-46-36

render: 'value' and render: 'percentage' both gives output labels in percentage only. Even if I don't set any label config in plugins, it automatically render chart with % labels.

Chartjs plugin labels with React

Hello,
I'm trying to connect chartjs-plugin-labels with React. I have the newest versions of chart.js, chartjs-plugin-datalabels, react-chartjs-2
I am doing everything according to #5 and I receive this error.
errorChart

   beforeDraw: function (chart) {
      if (!SUPPORTED_TYPES[chart.config.type]) {
        return;
      }
      chart._labels.forEach(function (label) {
        label.barTotalPercentage = {};
      });
    },

What am I doing wrong ?

 const state = {
    labels: appsLabel,

    datasets: [
      {
        data: percentData,
        backgroundColor: data.colors,
        borderColor: data.colors,
        borderWidth: 1,
        offset: 0,
      },
    ],
    plugins: [ChartDataLabels],
  };
  const options = {
    cutout: "80%",
    responsive: true,
    plugins: {
      legend: {
        display: false,
      },
      datalabels: {
        display: false,
        color: "white",
      },
      labels: [
        {
          render: "percentage",
          position: "outside",
          fontColor: "red",
          fontStyle: "bolder",
          textMargin: 6,
        },
      ],

      tooltip: {
        enabled: true,
        callbacks: {
          label: (tooltipItem) => {
            return `${tooltipItem.label}: ${tooltipItem.parsed} %`;
          },
        },
      },
    },
  };

and return:

<ChartProvider> 
        <Doughnut data={state} options={options} />
      </div>
</ChartProvider> 

Anyone have any idea? Thank you.

compilation problem in Angular

I used versions 5.0.0-beat and 4.0.0 respectively, it works but I am getting the following compilation error from webpackserver:
error TS2322: Type '{ legend: { display: false; }; title: { display: true; text: string; }; labels: { fontColor: string; fontStyle: string; fontSize: number; position: string; }; }' is not assignable to type '_DeepPartialObject<PluginOptionsByType<"pie">>'.
Object literal may only specify known properties, and 'labels' does not exist in type '_DeepPartialObject<PluginOptionsByType<"pie">>'.

labels: {
fontColor: '#000',
position: 'border',
}

Any ideas?

Here is my code:

import {ActiveElement,/* Chart, */ChartEvent, registerables} from 'chart.js';
import {ClosedAlertsGraphData, OpenAlertsGraphData} from './open-alerts-graph-data.model';
import {Router} from '@angular/router';
import {OpenAlertsGraphService} from "./open-alerts-graph.service";
import {GraphTypes, OpenAlerts} from '../../../main/open-alerts/open-alerts.model';
import Chart from 'chart.js/auto';
import { getChartLabelPlugin, PLUGIN_ID} from 'chart.js-plugin-labels-dv';

const canvasElmnt = this.elementRef.nativeElement.querySelector('canvas[name="openAlertsCanvas"]');
Chart.register(getChartLabelPlugin());
const router = this.router;
const closedAlertsData = data;
const product = this.product;
Chart.defaults.font.size = 12;
console.log("them 1: " + Chart.registry?.plugins.get(PLUGIN_ID));

    this.chart = new Chart(canvasElmnt, {
        type: 'pie',
        data: closedAlertsData,
        options: {
            responsive: true,
            plugins: {
                legend: {
                    display: false
                },
                title: {
                    display: true,
                    text: 'Chart.js Pie Chart',
                },
                labels: {
                    fontColor: '#000',
                    fontStyle: 'bold',
                    fontSize: 12,
                    position: 'border',
                }
            },
            onClick(event: ChartEvent, elements: ActiveElement[], chart: Chart) {
                if (elements.length > 0) {
                    const selectedDataset = closedAlertsData.datasets[elements[0].datasetIndex];
                    const activeElementIdx = elements[0].index;
                    const selectedAlertIds = selectedDataset.alertIds[activeElementIdx];
                    void router.navigate(['/alerts', product.toLowerCase(), 'list', 'Live'], {
                        queryParams: { alertsFilter: `id+in+${selectedAlertIds.join(',')}` }
                    });
                }
            }
        }
    });

Do you know if this should work with React?

Firstly, thanks for updating this for v3!

I'm trying to use this with React. I've npm installed the package, imported it into my file (import 'chart.js-plugin-labels-dv';), added labels:{render: 'label'} to the plugins object, but it doesn't seem to have any effect.

I'm using react-chartjs-2 (which works with v3 even though the name is a little misleading)

Should this work?

Thanks.

Chart.js 3.6.0 percentage, multiple labels not working

Hey, i've wanted to update my chart.js page with the newer version (3.6.0) and since the old labels plugin didn't work, i've found this plugin but seems that it doesn't work correctly at all!
Yes, you can specify render property with "value,label" but "percentage" doesn't work at all , displaying NaN% on pie and doughnut chart types. Also, as someone else specified here, multiple labels options doesn't seem to work at all, i need to display a label inside a pie slice and also an image outside, but with this it doesn't work :(

Congrats for the updated plugin and for your work, but do you think this will be updated and ready to be used as the legacy one? Thank you! ๐Ÿ‘

Not working for multiple datasets

This was also reported here

emn178#111

Example:

 const myChart = new Chart(document.getElementById('myChart'), {
  type: 'doughnut',
  data: {
	  labels: ['Value1', 'Value2', 'Value3', 'Value4'],
	  datasets: [{
	      backgroundColor: ['#00FF00', '#0000FF'],
	      data: [50, 50]
	    }, {
		  backgroundColor: ['#00FFFF', '#00FFFF'],
		  data: [50, 50],
	    }],
  },
  options: {
    plugins: {
	      tooltip: {
		        callbacks: {
		          label: function(context) {
		            const labelIndex = (context.datasetIndex * 2) + context.dataIndex;
		            return context.chart.data.labels[labelIndex] + ': ' + context.formattedValue + '%';
		          }
		        },
	      },
    	labels: {
	    	  render: 'image',
	          images: [
	              null, 
	              null, 
		          {
		          	src: 'http://simpleicon.com/wp-content/uploads/rocket.png',
			        width: 64,
			        height: 64
			      },
	              null
	         ],
	      },
    }
  }
});

How to position label on stacked bar chart?

I'm having a stacked bar chart and want to display the percentage at the top, but only for one dataset. Here's a screenshot of the current situation:

charts

With a custom render function I've hidden the values of the top-stacked bar. Now I'd need to have the percentage of the lower bar at the top of the canvas. For example at the height/level of the 1,600 mark. Is this possible?

Edit: maybe having the labels at position:absolute; top:0; or something alike would work.

Is it possible to wrap a text?

I have a label that's kinda long and I want to set a max width for the label so that it can wrap the text. Is that possible?
Or maybe with render function to add br tags (I don't know if render function accepts HTML tags)?

Cannot find Chart object in Vue app

I'm trying to integrate this package on my vue app but somehow an error pops out on the console
Cannot find Chart object.

<script>
   import Chart from 'chart.js/auto'
   import 'chart.js-plugin-labels-dv'
...
</script>

Did I miss anything here?

Allow for unlabeled charts along side labeled charts

Hello, first of all, thanks for making this repository available since the original one is outdated. A minor issue with the labeling is that they are enforced in every chart, which make it difficult for a page to have both labeled and unlabeled charts. It would be a good idea to check for the options if the labels tag is available or not before going to the process. I've made the changes in a local repository, I am going to create a pull request if you think it should be added.

Thanks,
Yousef Altaher

Typescript version of the plugin for Angular usage

Hi, I have migrated the plugin to typescript and I am using it with Angular.
If you'd like us to collaborate on publishing for typescript, please let me know.
Or you can add me as collaborator and I can open a pull request.

"npm i chart.js-plugin-labels-dv " not working

PS E:\sitafront\SitaFrontend-main> npm i chart.js-plugin-labels-dv
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/chart.js
npm ERR!   chart.js@"^2.8.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer chart.js@"^3.9.1" from [email protected]
npm ERR! node_modules/chart.js-plugin-labels-dv
npm ERR!   chart.js-plugin-labels-dv@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

Chat.register is not a function in VueJs3

Hello, do you have an idea on how I can use this with VueJs3? Currently I'm getting an error: Uncaught (in promise) TypeError: Chart.register is not a function

image

Thank you.

Not working with ng2-charts (Angular wrapper)

Thank you for making this plugin available. Unfortunately, I could not get it to work with ng2-charts (Angular wrapper) for my radar chart.

EDIT: I read you are looking for Angular contributors. I wish I could help, but I do not know how it works.

Does not work with chartjs-node-canvas (possible solution)

chartjs-node-canvas allows you to use chart.js in Node. It even supports loading plugins, so I tried giving this plugin a spin.
The way it works for plugins that rely on the global Chart object is it provides Chart in the initialization phase, assuming the plugins will just use it to register themselves and be done with it.
When this falls apart though is when this plugin uses the global Chart object in the function renderToElement. The commit that introduced the use of the global Chart object in this fashion is 34db117 at line 101.
I modified this function to use a version of helpers which I had previously saved from the global object.

previously

Label.prototype.renderToElement = function (dataset, arg, element, index) {
  ...
  ctx.font = Chart.helpers.fontString(...)
}

modified

if (typeof Chart === 'undefined') {
  console.error('Cannot find Chart object.');
  return;
}
const helpers = Chart.helpers;
...
Label.prototype.renderToElement = function (dataset, arg, element, index) {
  ...
  ctx.font = helpers.fontString(...)
}

I will open a pull request to clarify the changes I made. Let me know if this sounds good enough to be included, otherwise I'll keep it to myself.

Responsive labels within arc?

Is it possible to make the labels within the arc responsive? Or is this too complicated? This is unfortunately something I can't contribute as the maths looks too complicated for me, but if it's actually complex, I'd be willing to pay for it :)

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.