How to properly use formatting with chartjs? - javascript

I am trying to use formatting in Chart.js. I've configured the imports correctly, but it still doesn't display what I want
It doesn't work on my local pc. I uploaded the same code to codepen and it didn't work either. You can verify it here
var donutEl = document.getElementById("donut").getContext("2d");
var data = [4, 9, 5, 2];
var pieChart = new Chart(donutEl, {
type: 'doughnut',
data: {
datasets: [
{
data: [10, 20, 15, 5, 50],
backgroundColor: [ 'rgb(255, 99, 132)', 'rgb(255, 159, 64)', 'rgb(255, 205, 86)', 'rgb(75, 192, 192)', 'rgb(54, 162, 235)', ],
},
],
labels: ['Red', 'Orange', 'Yellow', 'Green', 'Blue'],
},
options: {
plugins: {
datalabels: {
formatter: (value) => {
return value + '%';
}
}
}
}
})
Any ideas what am I doing wrong? Thanks

As described here, you need to register the plugin:
Chart.register(ChartDataLabels);
Live example:
Chart.register(ChartDataLabels);
const donutEl = document.getElementById("donut").getContext("2d");
const data = [4, 9, 5, 2];
const pieChart = new Chart(donutEl, {
type: 'doughnut',
data: {
datasets: [{
data: [10, 20, 15, 5, 50],
backgroundColor: ['rgb(255, 99, 132)', 'rgb(255, 159, 64)', 'rgb(255, 205, 86)', 'rgb(75, 192, 192)', 'rgb(54, 162, 235)', ],
}, ],
labels: ['Red', 'Orange', 'Yellow', 'Green', 'Blue'],
},
options: {
plugins: {
datalabels: {
formatter: (value) => {
return value + '%';
}
}
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.0.0/chartjs-plugin-datalabels.min.js"></script>
<div class="flexWrapper">
<canvas id="donut" width="400" height="400"></canvas>
</div>

Related

ChartJS Doughnut Datasets with different thickness for each data value

I've been using ChartJS with PrimeNG, in Angular. Need to make a doughnut chart with i believe one dataset. I need to make it so each value has a different thickness, like this
So far I've tried a lot of things and read a lot of ChartJS documentation on Doughnut charts, but none of the options have helped me.
Here's how I implement my chart in HTML
<p-chart type="doughnut" [data]="donutData" [options]="donutChartOptions" class="h-10 my-4"></p-chart>
And here's the .ts to it
this.donutData = {
labels: ['A', 'B', 'C'],
datasets: [
{
data: [300, 50, 100],
backgroundColor: ['#F36F56', '#FFC300', '#B8A3FF'],
hoverBackgroundColor: ['#F36F56', '#FFC300', '#B8A3FF'],
},
],
};
this.donutChartOptions = {
cutout: 50,
plugins: {
legend: {
display: false,
labels: {
color: '#ebedef',
},
},
},
};
Here you can find the answer of your question: https://github.com/chartjs/Chart.js/issues/6195
I transferred the answer of "ex47" to chart.js 3
I put the constant "data" into the html file just to have less double code, it should better be in the javascript file.
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.9.1/dist/chart.min.js"></script>
<script>
const data = {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [
{
label: "# of Votes",
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
"rgba(255, 99, 132, 0.2)",
"rgba(54, 162, 235, 0.2)",
"rgba(255, 206, 86, 0.2)",
"rgba(75, 192, 192, 0.2)",
"rgba(153, 102, 255, 0.2)",
"rgba(255, 159, 64, 0.2)"
],
borderColor: [
"rgba(255, 99, 132, 1)",
"rgba(54, 162, 235, 1)",
"rgba(255, 206, 86, 1)",
"rgba(75, 192, 192, 1)",
"rgba(153, 102, 255, 1)",
"rgba(255, 159, 64, 1)"
],
borderWidth: 1
}
]
}
</script>
<style>
#chartWrapper {
width: 400px;
height: 400px;
}
</style>
</head>
<body>
<div id="chartWrapper">
<canvas id="myChart" width="400" height="400"></canvas>
</div>
</body>
<script src="myChart.js"></script>
</html>
myChart.js
var thickness = {
id: "thickness",
beforeDraw: function (chart, options) {
let thickness = chart.options.plugins.thickness.thickness;
thickness.forEach((item,index) => {
chart.getDatasetMeta(0).data[index].innerRadius = item[0];
chart.getDatasetMeta(0).data[index].outerRadius = item[1];
});
}
};
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx, {
type: "doughnut",
plugins: [thickness],
data: data,
options: {
plugins: {
thickness: {
thickness: [[100,130],[80,150],[70,160],[100,130],[100,130],[100,130]],
}
},
}
});
"Spirit04eK"'s solution sets the thickness in descending order of the magnitude of the value
myChart.js
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx, {
type: 'doughnut',
plugins: [
{
beforeDraw: function (chart) {
const datasetMeta = chart.getDatasetMeta(0);
const innerRadius = datasetMeta.controller.innerRadius;
const outerRadius = datasetMeta.controller.outerRadius;
const heightOfItem = outerRadius - innerRadius;
const countOfData = chart.getDatasetMeta(0).data.length;
const additionalRadius = Math.floor(heightOfItem / countOfData);
const weightsMap = datasetMeta.data
.map(v => v.circumference)
.sort((a, b) => a - b)
.reduce((a, c, ci) => {
a.set(c, ci + 1);
return a;
}, new Map());
datasetMeta.data.forEach(dataItem => {
const weight = weightsMap.get(dataItem.circumference);
dataItem.outerRadius = innerRadius + additionalRadius * weight;
});
}
}
],
data: data,
options: {
layout: {
padding: 10,
},
plugins: {
legend: false,
datalabels: {
display: false
},
},
maintainAspectRatio: false,
responsive: true,
}
});

Chart.js how to expand fidelity of only a portion of Y axis

See the chart picture below. We need to expand the Y axis from 0-10 so it increases to about 2x the size and shows each number. How do we do that? :D
code
const data = {
labels: dates,
datasets: [{
label: 'SIS',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: sis_data,
},
{
label: 'Mood',
backgroundColor: 'rgb(99, 255, 132)',
borderColor: 'rgb(99, 255, 132)',
data: mood_data,
},
{
label: 'Sleep',
backgroundColor: 'rgb(99, 132, 255)',
borderColor: 'rgb(99, 132, 255)',
data: sleep_data,
}]
};
const config = {
type: 'line',
data,
options: {}
};
var myChart = new Chart(
document.getElementById('myChart'),
config
);

ChartJS date reformatting for use?

I am having some trouble with my chartjs code. I have a date feed that send data to the charts seen below. While score, and day_7_average worked fine when converting to a list. I am having trouble the dates. the data format I receive is in the "const test" variable and I need it in the "const dates" variable. Based on the nature of the project I can not type them out every time. What is the best way of fixing this problem? thanks.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Sentiment</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.6/Chart.js"></script>
</head>
<style>
.bar { fill: steelblue; }
body { background-color: #1c142c; }
</style>
<body>
<div>
<h1 style="font: 200; color: white;">What are people saying on social media?</h1>
<canvas id="canvas""></canvas>
</div>
</body>
<script>
var ctx = document.getElementById("canvas").getContext('2d');
const test = ['2020-12-24', '2020-12-25', '2020-12-26', '2020-12-27', '2020-12-28', '2020-12-29', '2020-12-30', '2020-12-31']
const dates = ['2020-12-24','2020-12-25','2020-12-26','2020-12-27','2020-12-28','2020-12-29','20201-12-30','2020-12-31']
const score = [-2, -40, 81, -31, 34, -35, -24, -30]
const day_7_average = [0, -6, 3, -2, 5, 5, 0, -7]
window.chartColors = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(75, 192, 192)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(201, 203, 207)'
};
const colours = score.map((value) => value < 0 ? 'rgb(255, 99, 132)' : 'rgb(75, 192, 192)');
var chartData = {
labels: dates,
datasets: [{
type: 'line',
label: '7 day average',
backgroundColor: 'rgb(201, 203, 207)',
borderColor: 'rgb(201, 203, 207)',
borderWidth: 2,
fill: false,
data: day_7_average,
},
{
type: 'bar',
label: 'Sentiment Score',
backgroundColor: colours,
data: score
}]
};
window.onload = function() {
window.myMixedChart = new Chart(ctx, {
type: 'bar',
data: chartData,
options: {
responsive: true,
tooltips: {
mode: 'index',
intersect: false,
}
}
});
};
Well... it may be a sloppy workaround but try this:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Sentiment</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.6/Chart.js"></script>
</head>
<style>
.bar { fill: steelblue; }
body { background-color: #1c142c; }
</style>
<body>
<div>
<h1 style="font: 200; color: white;">What are people saying on social media?</h1>
<canvas id="canvas"></canvas>
</div>
</body>
<script>
var ctx = document.getElementById("canvas").getContext('2d');
const test = [''2020-12-24'',
''2020-12-25'',
''2020-12-26'',
''2020-12-27'',
''2020-12-28'',
''2020-12-29'',
''2020-12-30'',
''2020-12-31''];
var i;
dates_tmp = [];
for (i = 0; i < test.length; i++) {
dates_tmp.push(String(test[i].replaceAll("'", "")));
}}
const dates = dates_tmp;
const score = [-2, -40, 81, -31, 34, -35, -24, -30]
const day_7_average = [0, -6, 3, -2, 5, 5, 0, -7]
window.chartColors = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(75, 192, 192)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(201, 203, 207)'
};
const colours = score.map((value) => value < 0 ? 'rgb(255, 99, 132)' : 'rgb(75, 192, 192)');
var chartData = {
labels: dates,
datasets: [{
type: 'line',
label: '7 day average',
backgroundColor: 'rgb(201, 203, 207)',
borderColor: 'rgb(201, 203, 207)',
borderWidth: 2,
fill: false,
data: day_7_average,
},
{
type: 'bar',
label: 'Sentiment Score',
backgroundColor: colours,
data: score
}]
};
window.onload = function() {
window.myMixedChart = new Chart(ctx, {
type: 'bar',
data: chartData,
options: {
responsive: true,
tooltips: {
mode: 'index',
intersect: false,
}
}
});
};
</script>
</html>
( Oh and by the way: You've got an unexpected " in line 16 )

Displaying Data on a Pie chart in ChartsJs

I was able to create this doughnut chart that displays data. However, now that I look at it, I would like add the number value of the foods (100,200,300) below, on a second line, instead of having next to the food item itself. Is there a way to do this? I was thinking that since this is a nested array, looping through it may work? Any thoughts?
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
label1: [["Pizza: 100"], ["Hot Dogs: 200"], ["Burgers:300"]],
datasets: [{
label: '# of Votes',
data: [12, 19, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)'
],
borderWidth: 1
}]
},
options: {
tooltips: {
callbacks: {
title: function(tooltipItem, data, label1, label2) {
return data ['label1'][tooltipItem[0]['index']];
},
label: function(tooltipItem, data) {
return data['datasets'][0]['data'][tooltipItem['index']];
},
afterLabel: function(tooltipItem, data) {
var dataset = data['datasets'][0];
var percent = Math.round((dataset['data'][tooltipItem['index']] / dataset["_meta"][0]['total']) * 100)
return '(' + percent + '%)';
}
},
backgroundColor: '#FFF',
titleFontSize: 16,
titleFontColor: '#0066ff',
bodyFontColor: '#000',
bodyFontSize: 14,
displayColors: false
}
}
});
<div>
<canvas id="myChart" height="100"></canvas>
<div id="chartjs-tooltip">
<table></table>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js">
</script>

How to change the label color in chart.js?

I have a pie chart defined like so,
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: data.labels,
datasets: [{
data: data.values,
backgroundColor: [
'rgb(255, 99, 132)',
'rgb(54, 162, 235)',
'rgb(255, 206, 86)',
'rgb(75, 192, 192)',
'rgb(153, 102, 255)',
'rgb(255, 159, 64)',
'rgb(204, 255, 64)',
'rgb(64, 159, 255)',
'rgb(175, 64, 255)'
],
options: {
responsive : true,
}
}],
fontColor : '#FFFFFF'
}
});
how the chart looks,
This however is setting the font color of the labels to black, how can I change this color. Any pointers on this is highly appreciated. Thanks!
You can change the font color of legend­'s label, in the following way ...
options: {
legend: {
labels: {
fontColor: 'white'
}
},
...
}
ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ
var chart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ['A', 'B', 'C', 'D', 'E'],
datasets: [{
data: [1, 1, 1, 1, 1],
backgroundColor: [
'rgb(255, 99, 132)',
'rgb(54, 162, 235)',
'rgb(255, 206, 86)',
'rgb(75, 192, 192)',
'rgb(153, 102, 255)'
]
}]
},
options: {
legend: {
labels: {
fontColor: 'white' //set your desired color
}
}
}
});
canvas{background: #222}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="ctx"></canvas>
To change label color with Chart.js, you must set the fontColor.
to set the fontColor of the labels by setting the fontColor in the options object property.
for example;
fontColor: "white", // set color
or you can visit the following link : https://thewebdev.info/2022/06/27/how-to-change-label-color-with-chart-js-and-javascript/
Sorry to unbury this but trying any solutions and only this works. create plugin before chart :
Chart.plugins.register({
beforeDraw: function(c) {
c.legend.options.labels.fontColor = 'hsl(0,0%,85%)';
}
});
var chart = new Chart(ctx, {
....
The only solution i found to work for this problem is the following line
Chart.defaults.color = '#fff';
Hope it helps

Categories