ChartJS: Percentage labels - javascript

First of all, I would like to say that I'm a student learning programming for around a month, so expect to see many mistakes.
I'm working on a website where I use a chart from the ChartJs library. I have one outer circle that shows the hours worked on the company and the hours left to reach the monthly goal. The inner circle shows the days of the month and the days left of the month. Here is the code:
const data = {
labels: ['Summe', 'Noch um Ziel zu erreichen', 'Tage', 'Verbleibende Tage im Monat'],
datasets: [
{
backgroundColor: ['#5ce1e6', '#2acaea'],
data: [studenGesamt, (800 - studenGesamt)]
},
{
backgroundColor: ['#cd1076', '#8b0a50'],
data: [dayD, (23 - dayD)]
},
]
};
// Configuration of the pie chart
let outterChart = new Chart(chart, {
type: 'pie',
data: data,
options: {
responsive: true,
plugins: {
legend: {
labels: {
render: 'percentage',
fontColor: ['green', 'white'],
precision: 2,
generateLabels: function(chart) {
// Get the default label list
const original = Chart.overrides.pie.plugins.legend.labels.generateLabels;
const labelsOriginal = original.call(this, chart);
// Build an array of colors used in the datasets of the chart
var datasetColors = chart.data.datasets.map(function(e) {
return e.backgroundColor;
});
datasetColors = datasetColors.flat();
// Modify the color and hide state of each label
labelsOriginal.forEach(label => {
// Change the color to match the dataset
label.fillStyle = datasetColors[label.index];
});
return labelsOriginal;
}
},
onClick: function(mouseEvent, legendItem, legend) {
// toggle the visibility of the dataset from what it currently is
legend.chart.getDatasetMeta(
legendItem.datasetIndex
).hidden = legend.chart.isDatasetVisible(legendItem.datasetIndex);
legend.chart.update();
}
},
tooltip: {
callbacks: {
label: function(context) {
const labelIndex = (context.datasetIndex * 2) + context.dataIndex;
return context.chart.data.labels[labelIndex] + ': ' + context.formattedValue;
}
}
},
}
},
});
I want to show the percentage of each section of the pie chart on the pie chart. For that I found the plugin "chartjs-plugin-labels", and I added the following link on the script tag so I can use it on my website:
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<script src="script.js"></script>
<script src="https://cdn.jsdelivr.net/gh/emn178/chartjs-plugin-labels/src/chartjs-plugin-labels.js"></script>
On my code, I added the following code (I didn't add the closing brackets here as they are further down in the code and I just wanted to show this small specific part of the code):
plugins: {
legend: {
labels: {
render: 'percentage',
fontColor: ['green', 'white'],
precision: 2,
However, this code is not working and no percentages are showing up on the chart. I assume I have done something wrong, maybe on the CDN link or on the code itself, but I can't figure out. If someone could help me, I would really appreciate it! Here is a picture of the chart so you can get an idea of what I exactly want:

The plugin you are trying to use is outdated and doesnt work with chart.js version 3, you can use datalabels plugin.
When using the datalabels plugin you need to use the formatter function to change the values to percentages and you will need to register the plugin:
Chart.register(ChartDataLabels);
const data = {
labels: ['Summe', 'Noch um Ziel zu erreichen', 'Tage', 'Verbleibende Tage im Monat'],
datasets: [{
backgroundColor: ['#5ce1e6', '#2acaea'],
data: [200, (800 - 200)]
},
{
backgroundColor: ['#cd1076', '#8b0a50'],
data: [4, (23 - 4)]
},
]
};
var ctx = document.getElementById('chartJSContainer').getContext('2d');
// Configuration of the pie chart
let outterChart = new Chart(ctx, {
type: 'pie',
data: data,
options: {
responsive: true,
plugins: {
datalabels: {
color: 'white',
formatter: (val, ctx) => {
const totalDatasetSum = ctx.chart.data.datasets[ctx.datasetIndex].data.reduce((a, b) => (a + b), 0);
const percentage = val * 100 / totalDatasetSum;
const roundedPercentage = Math.round(percentage * 100) / 100
return `${roundedPercentage}%`
}
},
legend: {
labels: {
generateLabels: function(chart) {
// Get the default label list
const original = Chart.overrides.pie.plugins.legend.labels.generateLabels;
const labelsOriginal = original.call(this, chart);
// Build an array of colors used in the datasets of the chart
var datasetColors = chart.data.datasets.map(function(e) {
return e.backgroundColor;
});
datasetColors = datasetColors.flat();
// Modify the color and hide state of each label
labelsOriginal.forEach(label => {
// Change the color to match the dataset
label.fillStyle = datasetColors[label.index];
});
return labelsOriginal;
}
},
onClick: function(mouseEvent, legendItem, legend) {
// toggle the visibility of the dataset from what it currently is
legend.chart.getDatasetMeta(
legendItem.datasetIndex
).hidden = legend.chart.isDatasetVisible(legendItem.datasetIndex);
legend.chart.update();
}
},
tooltip: {
callbacks: {
label: function(context) {
const labelIndex = (context.datasetIndex * 2) + context.dataIndex;
return context.chart.data.labels[labelIndex] + ': ' + context.formattedValue;
}
}
},
}
},
});
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.0.0/chartjs-plugin-datalabels.js"></script>
</body>

Related

How to highlight specific Point with Highcharts Js

I have a simple Highchart with a dataset of up to 1000 datas. There are only y values the x values are generated automatically. Also, the values come from my nodejs server so please don't be surprised about the notation.
Now I want 3 special values whose x and y values are known to be highlighted. In which way doesn't matter for now.
One possibility would be to show the point at the location, otherwise they are not displayed. The problem I have is that I don't know how to control a specific point.
var chart1 = new Highcharts.Chart({
chart: {
renderTo: 'chart-emg1',
type: 'line'
},
title: {
text: 'EMG 1'
},
xAxis: {
tickInterval: 1
},
yAxis: {
title: { text: 'Voltage'}
},
series: [{
data: [<%-data1 %>]
}]
});
You can use the load event and update specific points. For example:
events: {
load: function() {
this.series[0].points.forEach(point => {
const isPointToHighlight = pointsToHighlight.some(
p => p.x === point.x && p.y === point.y
);
if (isPointToHighlight) {
point.update({
color: 'red',
marker: {
enabled: true
}
}, false);
}
});
this.redraw();
}
}
Live demo: http://jsfiddle.net/BlackLabel/tLd3j78f/
API Reference:
https://api.highcharts.com/highcharts/chart.events.load
https://api.highcharts.com/class-reference/Highcharts.Point#update

Highstock Charts React: Generating chart with multiple series is displayed incorrectly

I'm trying to create a Component that wraps a Highstock chart.
It takes charts and chartHeight as props, and I'm generating the chart options like so:
setChartOptions({
chart: {
height: (props.charts.length) * props.chartHeight,
},
credits: {
enabled: false
},
title: {
text: 'Title'
},
rangeSelector: {
selected: 0,
buttons: [],
inputEnabled: false
},
tooltip: {
split: true
},
series: buildSeries(),
yAxis: buildYAxis()
})
I'm using the functions buildSeries and buildYAxis:
const buildSeries = () => {
let series = [];
props.charts.forEach((chart, index) => {
series.push({
type: chart.type,
name: chart.title,
data: chart.data,
yAxis: index,
color: chart.color
})
})
return series;
}
const buildYAxis = () => {
let yAxis = [];
props.charts.forEach((chart, index) => {
yAxis.push({
labels: {
align: 'right',
x: -3
},
title: {
text: chart.title,
},
height: props.chartHeight,
top: index * props.chartHeight,
lineWidth: 2,
resize: {
enabled: true
},
offset: 0
})
})
return yAxis;
}
But the charts are displayed incorrectly:
As the picture shows, the first chart is displayed in the very bottom (Blue) and the large gap between the Title and the chart is supposed to hold the first chart.
When I enter the return values of buildSeries and buildYAxis the chart is displayed correctly.
I used the following link as an example of a functioning chart:
https://www.highcharts.com/demo/stock/candlestick-and-volume
Am I missing something with the initialization of the options? Or is this a bug within Highstock charts?
Thank you

charts js, doughnut chart not rendering tooptips correctly

i have a multilevel donut chart but it is not rendering correctly here is code
the problem is, onmouseover on all green parts it says objects, on all grey parts it says products, solution i would like is, on outer ring it should say products, in middle objects, and inner most should be materials, grey areas should just show number. here is a jsfiddle of the problem
Code:
var op=93;
var ap=99;
var mp=66;
var ctx = new Chart(myChart, {
type: 'doughnut',
data: {
labels: ['Objects', 'Products', 'Materials'],
datasets: [{
label: 'Objects',
data: [op, 100 - op],
backgroundColor: ['#006a4e','#eeeeee'],
hoverOffset: 4
},{
label: 'Products',
data: [ap, 100 - ap],
backgroundColor: ['#2e856e', '#eeeeee'],
hoverOffset: 4
},
{
label: 'Materials',
data: [mp, 100 - mp],
backgroundColor: ['#5ca08e', '#eeeeee'],
hoverOffset: 4
}
]
},
options: {
//cutoutPercentage: 40,
height: 200,
width:200
}
});
You can achieve that fairly simple with Chart.JS 2.7.2. Add labels to each dataset like this:
data: {
labels: ['Existing', 'Non'],
datasets: [
{
labels: ['Objects', 'Non-objects'],
...
}, {
labels: ['Products', 'Non-products'],
...
},
{
labels: ['Materials', 'Non-materials'],
...
}
]
}
And add the following label tooltip callback:
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var dataset = data.datasets[tooltipItem.datasetIndex];
var index = tooltipItem.index;
return dataset.labels[index] + ": " + dataset.data[index];
}
}
}
Demo: https://jsfiddle.net/adelriosantiago/fxd6vops/3/
I am sure it is possible with Chart.JS > 3.0 too but I have no idea how since quite a few things changed in the structure.
I had a same problem which took a lot of time but what worked in the end was importing these elements and initialising them ..
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from 'chart.js';
ChartJS.register(ArcElement, Tooltip, Legend);
these are the elements that helps make the entire chart. you can't skip them

old yAxis ticks do not get removed (chartjs, react-chartjs-2 wrapper)

When i draw a chart with 4 lines, each with its own data ofc, i programmatically create the options for the LineChart that has 4 Yaxis, first one on the left and the rest on the right side. Now, after the chart is drawn and i de-select some datasources from the list (less lines to draw), the now-obsolete yAxis ticks stay there, even when the chart correctly draws only the selected lines, and the options are updated as well correctly. I cant think of a way to remove them!
I have googled for 2 days and cant find a solution. I am using react in functional style and it makes things more complicated because every advice seems to be in the classic style.
I am using react-chartjs-2 wrapper as well, if this helps.
I am also quite new to react, and asking in Stackoverflow, so please cut me some slack :)
I assume the chart is being re-rendered or something because the amount of lines etc do change.
In the images, the "createYaxis" that is shown in the console.log is the generated yAxes- part of the options object (which is functional otherwise). The problem yAxises are on the right side in red and yellow. Images show before and after situation.
Image of the options-object generated by the code below the img:
var yAxisItems = [];
function createYaxises (num){
var arr = [];
for (var i=0;i<num.length;i++){
if (i===0){
arr.push({
display: true,
id: i,
type: 'linear',
position: 'left',
gridLines: {
display:false,
//color: 'blue'
},
ticks: {
fontColor: lineColourArray[i],
fontSize: 14,
}
})
}
else {
arr.push({
display: true,
id: i,
type: 'linear',
position: 'right',
gridLines: {
display:false,
//color: 'blue'
},
ticks: {
display:true,
fontColor: lineColourArray[i],
fontSize: 14,
}
})
}}
yAxisItems = arr;
console.log("createyaxis arr: " , arr);
console.log("createyaxis: " , yAxisItems); //JSON.stringify(yAxisItems));
}
//get data for selected sensors and set it to chart data
const handleGetSelectedSensorData = function () {
var d = getSelectedSensorData();
console.log("d: ", d);
var dSets = [];
if (d[0]){
d.map((dItem,index)=> {
var newDsetData =[];
if (dItem.data){
dItem.data.map((innerDataItem)=> {
var dSet = {};
dSet.x = innerDataItem.timestamp;
dSet.y = innerDataItem.v;
newDsetData.push(dSet);
})
var newset = {
data: newDsetData,
label: dItem.sensorTag,
borderColor: lineColourArray[index],
fill: false,
pointRadius: 1.5,
backgroundColor:lineColourArray[index],
borderWidth: 2,
showLine: true,
pointHoverRadius: 5,
lineTension: 1,
};
dSets.push(newset);
}})
var dDataTemp = {};
var optionsTemp = new Object();
dDataTemp.datasets =dSets;
//create yaxises only once
createYaxises(dDataTemp.datasets);
//more than one set (TODO)
//console.log("dDataTemp.datasets : ", dDataTemp.datasets)
if (dDataTemp.datasets.length >1){
console.log("dset > 1");
for(var i=0;i< dDataTemp.datasets.length;i++) {
dDataTemp.datasets[i].yAxisID = i;
console.log("setting options");
optionsTemp ={
tooltips: {
enabled: true,
intersect:false,
mode:'x',
callbacks: {
title: function(tooltipItem, data) {
var toSplit = tooltipItem[0].label.split(",");
return (toSplit[0]);
},
label: function (tooltipItem) {
var split = tooltipItem.xLabel.split(',');
//return ( Number(tooltipItem.yLabel).toFixed(3));
return (split[2] + " : " + Number(tooltipItem.yLabel).toFixed(3));
}
},
},
hover: {
mode: 'nearest',
intersect: true,
},
title:{
display:true,
text:'Valittu sensoridata',
fontSize:20
},
legend:{
display:true,
position:'right'
},
scales: {
xAxes: [{
display: true,
type: 'time',
ticks: {
}
}],
yAxes:
yAxisItems
}
}
}
setOptions(optionsTemp);
console.log("options: " , optionsTemp);
setdData(dDataTemp);
}}
else {
console.log("error in handleGetSelectedSensorData()");
}
}
And the Line is just added like this:
<Line data={dData} options = {options} />
Instead of setting display: true set display: 'auto', this will make the axis dissapear as long as there is no dataset visable that is linked to that scale, as soon as a dataset becomes visable that is linked to that scale it will show the scale again.
Doc: https://www.chartjs.org/docs/master/axes/cartesian/#common-options-to-all-axes

Add HTML to label of bar chart - chart js

I am using the chart js to display a bar graph. It's working correctly on normal instances, but I am willing to change the color or a small portion of the label i.e, I want to include some HTML on the label of the bar chart. But, it isn't rendering the HTML instead it is showing plain HTML text.
If it is not possible, it's okay for me if there is another way to achieve this like, change the color of the price and keep the name as it is.
let $js_dom_array = ["43.28", "93.13"];
let $js_am_label_arr = ["<span>$0</span> None", "<span class='text-danger'>$23.63</span> Handicap Accessible"];
let ctx2 = document.getElementById("barChart").getContext("2d");
let chart = new Chart(ctx2, {
type: 'bar',
data: {
labels: $js_am_label_arr,
datasets: [{
label: 'Amenity Name',
data: $js_dom_array,
backgroundColor: 'rgba(26,179,148,0.5)',
borderColor: 'rgba(75, 192, 192, 1)',
borderWidth: 1
}]
},
options: {
responsive: true,
maintainAspectRatio: true,
legendCallback: function(chart) {
var text = [];
for (var i=0; i<chart.data.datasets.length; i++) {
console.log(chart.data.datasets[i]); // see what's inside the obj.
text.push(chart.data.datasets[i].label);
}
return text.join("");
},
tooltips: {
"enabled": false
},
scales: {
xAxes: [{
stacked: false,
beginAtZero: true,
ticks: {
stepSize: 1,
min: 0,
autoSkip: false,
callback: function(label, index, labels) {
if (/\s/.test(label)) {
return label.split(" ");
}else{
return label;
}
}
}
}]
},
animation: {
duration: 0,
onProgress: function() {
var chartInstance = this.chart,
ctx = chartInstance.ctx;
ctx.font = Chart.helpers.fontString(16, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
this.data.datasets.forEach(function(dataset, i) {
var meta = chartInstance.controller.getDatasetMeta(i);
meta.data.forEach(function(bar, index) {
if (dataset.data[index] > 0) {
let data = dataset.data[index];
ctx.fillText('$'+Math.round(data), bar._model.x, bar._model.y - 5);
}
});
});
}
},
}
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<canvas id="barChart" height="140"></canvas>
</div>
#Note: Here, you might see that the data in $js_am_label_arr is already an HTML element, but if there is something from where I could pass the array of the raw values and the convert in HTML than I could pass the raw value (without) as well.
Currently $js_am_label_arr is created as:
if($avg_amount < 0){
$text_color = 'text-danger';
$avg_amount_text = "<span class='text-danger'>$".abs($avg_amount)."</span>";
}else{
$text_color = '';
$avg_amount_text = "<span>$".abs($avg_amount)."</span>";
}
$am_label_arr[] = $avg_amount_text.' '.$fv['amenity_name'];
Update:
Expected Output
So if the value is negative for example in the above case, its -$23.63. In this case, I want the label to be ($23.63)[in color red] followed by the name Handicap Accessible. This can be seen at the result as well, text-danger classes is added to show that part in red color.
As you are open to any plugin so i suggest you to use HighCharts to achieve above case . In below demo code i have just passed the label value to categories in xAxis and done a little change to span tag . i.e : i have added inline css to span where you need to display color red .
Here is demo code :
var chart;
let $js_dom_array = [43.28, 93.13];
let $js_am_label_arr = ["<span>$0</span> None", "<span style='color:red'>$23.63</span> Handicap Accessible"];
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'chart_container', //under chart_container chart will display
defaultSeriesType: 'bar', //bar grapgh
backgroundColor: '#CCCCCC',
type: 'column' //to display in columns wise
},
plotOptions: {
bar: {
colorByPoint: true,
dataLabels: {
enabled: false
}
}
},
title: {
text: 'Something.... '
},
xAxis: {
categories: $js_am_label_arr, //for value in labels
},
series: [{
name: 'Amenity Name',
data: $js_dom_array //array value to plot data
}]
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/gantt/highcharts-gantt.js"></script>
<div id="chart_container"></div>
You can change the color when you hover the label, with the tooltips callback
Move your mouse over the bar
let $js_dom_array = [43.28, 93.13];
let $js_am_label_arr = ["$0", "$23.63"];
let ctx2 = document.getElementById("barChart").getContext("2d");
let chart = new Chart(ctx2, {
type: 'bar',
data: {
labels: $js_am_label_arr,
datasets: [{
backgroundColor: 'rgba(26,179,148,0.5)',
label: 'Amenity Name',
data: $js_dom_array,
}]
},
options: {
responsive: true,
maintainAspectRatio: true,
tooltips: {
enable: true,
callbacks: {
labelTextColor: function(tooltipItem, chart) {
if(tooltipItem.index === 1)
return 'red';
}
}
},
scales: {
xAxes: [{
stacked: false,
beginAtZero: true,
ticks: {
stepSize: 1,
min: 0,
autoSkip: false,
fontColor: "red",
callback: function(label, index, labels) {
if (/\s/.test(label)) {
return label.split(" ");
}else{
return label;
}
}
}
}]
}
}
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<canvas id="barChart" height="140"></canvas>
</div>
As far as i know, its not possible to do what you want.
With the current version (v2.9.3) its not even possible to change the color for specifics X ticks labels, you can only change the color for every label with:
options: {
scales: {
yAxes: [{
ticks: {
fontColor: "red",
}
}],
xAxes: [{
ticks: {
fontColor: "red",
}
}]
}
}
There is a workaround with version v2.6.0 (as you tagged this version, i imagine you are using it) wich you can pass an array of colors to fontColor, like: fontColor: ["red","green"], but you need to change some code lines of chartjs and yet you cannot change just a specific part of the text of axis tick label as you want.
If you have interested in this solution, you can check it here Add possibility to change style for each of the ticks
But again, this solution is related to an older version of chartjs and i dont know what features you lose here.
Looks like it will be able to change the color for each ticks in version 3.0, but this version isnt released yet.
UPDATED
I done a simple example here with c3/d3 js. but it has some points:
It take a little time to show Labels updated when chart is rendered.
On changeTickLabel i did a harded code to check value and then append the text (like 'Handicap Accessible'). So here you will need to find logic that is better to you.
var chart = c3.generate({
onrendered: function () { changeTickLabel() },
data: {
columns: [
['data1', 43.28, 93.13]
],
type: 'bar',
},
axis: {
x : {
type: 'category',
categories: ["$0", "$23.63"],
tick: {
multiline:false,
culling: {
max: 1
},
},
},
}
});
function changeTickLabel(){
d3.selectAll('.c3-axis-x .tick tspan')
.each(function(d,i){
var self = d3.select(this);
var textValue = self.text();
if(textValue !== '$0'){
self.style("fill", "red");
self.append('tspan').style("fill", "black").text(' Handicap Accessible');
}
else {
self.append('tspan').text(' None');
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.16.0/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.7.20/c3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="chart"></div>

Categories

Resources