davideviolante / chartjs-plugin-labels Goto Github PK
View Code? Open in Web Editor NEWThis project forked from emn178/chartjs-plugin-labels
Plugin for Chart.js to display percentage, value or label in Pie or Doughnut.
License: MIT License
This project forked from emn178/chartjs-plugin-labels
Plugin for Chart.js to display percentage, value or label in Pie or Doughnut.
License: MIT License
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?
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.
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.
I have the same code that you have in the documentaion, but I can't figure out what it is wrong. Can you check it, please? Here's the code: https://codesandbox.io/s/polar-bs-plugin-wjcsz6?file=/App.tsx
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(',')}` }
});
}
}
}
});
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.
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! ๐
This was also reported here
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
],
},
}
}
});
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:
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.
Will this plugin become compatible with chart.js 4.2.1?
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)?
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?
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
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.
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.
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.
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.
Label.prototype.renderToElement = function (dataset, arg, element, index) {
...
ctx.font = Chart.helpers.fontString(...)
}
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.
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 :)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.