How to add datalabels in stacked bar/line chart in chartJS - javascript

I am trying to add the datalabels onto my stacked bar/line chart in chartJS specifically at the line chart area. Because the values are not aligned with the Y-Axis, therefore I wanted to use chartJS datalabels plugin to show the values on top of the line chart only for better clarification when it is printed out.
What I tried:
#1 putting into config
const config = {
type: 'line',
data: data,
options: {
plugins: {
datalabels: {
anchor: 'end',
align: 'top',
formatter: function(value, context) {
return GetValueFormatted(value);
},
borderRadius: 4,
color: 'white',
font: {
weight: 'bold'
},
formatter: Math.round,
padding: 6
},
title: {
display: true,
text: 'Menu Performance Chart'
},
},
scales: {
y: {
stacked: true
}
}
},
};
#2 putting into specific dataset
const data = {
labels: labels,
datasets: [{
label: 'Sub Total Sales (RM)',
data: [
'111',
'22',
'31',
'12',
'71',
'110',
'22',
],
borderColor: 'rgb(255, 99, 132)',
backgroundColor: 'rgba(255, 99, 132, 0.2)',
stack: 'combined',
type: 'bar'
},
{
label: 'Total Amount Sold',
data: [
'11',
'2',
'3',
'1',
'7',
'10',
'2',
],
borderColor: 'rgb(255, 159, 64)',
backgroundColor: 'rgba(255, 159, 64, 0.2)',
stack: 'combined',
datalabels: {
color: '#FFCE56'
}
},
]
};
I even tried the two at the same time to see if there were any results. Could anyone assist me with this? Thank you in advance.
Here is my code demo in JSFiddle:
https://jsfiddle.net/4gat7rzs/4/

The plugin is not registered. See doc: https://chartjs-plugin-datalabels.netlify.app/guide/getting-started.html#registration
You should add the datalabels plugin instance to the chart config:
const config = {
type: 'line',
data: data,
plugins: [ChartDataLabels], // <- MUST BE ADDED
options: {
....

Related

problem with chart js pie chart dataset data

This is the output of the code which I don't want since each data sits inside the other, I followed the documentation and other code examples but to no avail.
here is my code
let labelCharts: string[] = ['Supplier Debt', 'Raw Material Cost', 'Product Cost', 'Customer Debt'];
let myDoughnutChart = new Chart(this.ctx, {
type: 'pie',
data: {
labels: labelCharts,
datasets: [{
backgroundColor: "#3e95cd",
borderWidth: 10,
label: 'Supplier Debt',
data: [1, 5, 1],
},
{
data: rawMatCostArr,
backgroundColor: "#8e5ea2",
borderWidth: 10,
label: 'Raw Material Cost',
},
{
data: productCostArr,
backgroundColor: "#3cba9f",
borderWidth: 10,
label: 'Product Cost',
},
{
data: agentsDebtArr,
backgroundColor: "#e8c3b9",
borderWidth: 10,
label: 'Customer Debt',
}
]
},
options: {
maintainAspectRatio: false,
title: {
display: true,
text: 'Total'
}
}
});
note that each variable inside the data property is an array
To achieve the behaviour you want you only need 1 dataset and put the sum of the data in it. If you use it like shown in this config you get the desired outcome:
const config = {
type: 'pie',
data: {
labels: ['Supplier Debt', 'Raw Material Cost', 'Product Cost', 'Customer Debt'],
datasets: [{
backgroundColor: ["#3e95cd","#8e5ea2","#3cba9f","#e8c3b9"],
borderWidth: 10,
label: 'Supplier Debt',
data: [1, 5, 3,6],
}
]
},
options: {
maintainAspectRatio: false,
title: {
display: true,
text: 'Total'
}
}
};
You might want to decrease the border with since it will make your chart look a lot better.

Chart js label issue in react js

I used chart js to display data but the labels are not applying properly, it applies to single column
my chart code is :
var dates = ['Lonely','Relationship','Anexity','Hurt','Fear'];
var ctxallSelect = document.getElementById('Emotional');
window.allEmotion = new Chart(ctxallSelect, {
type: 'bar',
data: {
labels: dates,
datasets: [{
label: 'Lonely',
backgroundColor: [
'rgb(0, 156, 182)'
],
borderColor: [
'rgb(0, 156, 182)'
],
data:[this.state.Lonely],
fill: false,
}, {
label: 'Relationship',
fill: false,
backgroundColor: [
'rgb(0, 156, 182)'
],
borderColor: [
'rgb(0, 156, 182)'
],
data: [this.state.Relationship],
},
But my chart label appear as below:
Your issue is related to way you are setting your data inside dataset.
I did a live demo for you solving the issue:
https://codesandbox.io/s/boring-banach-lvffs?file=/src/App.js
Data is an array, each position of that array means one column, so you should do like:
datasets: [
{
label: "Lonely",
.....
data: [30]
},
{
label: "Relationship",
.....
data: [0,45]
},

ChartJS - Labels getting cutoff using datalabels plugin

I have a simple bar chart and I'm using the datalabels plugin to place labels inside each bar and at the top.
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['One', "Two"],
datasets: [{
data: [40, .5],
backgroundColor: [
'rgba(255, 99, 132)',
'rgba(54, 162, 235)'
],
borderWidth: 1
}]
},
options: {
legend: {
display: false
},
tooltips: {
enabled: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
max: 40
},
}],
xAxes: [{
maxBarThickness: 50
}]
},
plugins: {
datalabels: {
display: true,
anchor: 'end',
align: 'top',
color: 'white',
offset: -30,
font: {
weight: 'bold',
size: 14
}
}
}
}
});
But sometimes, I'll have a value that doesn't allow enough room for the label. See second bar on https://jsfiddle.net/myckxLun/1/.
I want to make sure I have X amount of room for these labels. I've tried minBarLength for the Y-axis - but all this does is force the bar length to be a min pixel value and doesn't adjust the graph (i.e. the bar length is inaccurate).
Ideas on how I can fix this? Thanks!

Multiple Graphs on one page

I have a website displaying inplay stats from football matches, I have a large number of stats and want to try and get away from just line after line of numbers in a table. Im using jquery datatables and have added a drop down for each row of data with more stats. In this drop down I would like a canvas.js radar graph
The problem is I cant find a way round having to initialise each chart with lots of code and that code would then be repeated on every line of the table, as a busy time that could be over 100 matches
below is the code of what I want to achieve but I want that in every row of a datatable, ideally I would like to initialise the graphs once and just have a single line of code in my datatable with the numbers
Any ideas ?
<!doctype html>
<html>
<head>
<title>Radar Chart</title>
<script src="dist/2.8.0/Chart.min.js"></script>
<script src="utils.js"></script>
<style>
canvas {
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
</style>
</head>
<body>
<button id="save-btn">Save Chart Image</button>
<div style="width:40%">
<canvas id="canvas"></canvas>
</div>
<script>
var randomScalingFactor = function() {
return Math.round(Math.random() * 100);
};
var color = Chart.helpers.color;
var config = {
type: 'radar',
data: {
labels: [['Shots on', ' Target'], ['Shots Off', 'Target'], 'Corners', 'possession (out of 10)'],
datasets: [{
label: 'Home team',
backgroundColor: color(window.chartColors.red).alpha(0.2).rgbString(),
borderColor: window.chartColors.red,
pointBackgroundColor: window.chartColors.red,
data: [
'5',
'7',
'4',
'6',
'2'
]
}, {
label: 'Away Team',
backgroundColor: color(window.chartColors.blue).alpha(0.2).rgbString(),
borderColor: window.chartColors.blue,
pointBackgroundColor: window.chartColors.blue,
data: [
'2',
'1',
'3',
'5',
'0'
]
}]
},
options: {
legend: {
position: 'top',
},
title: {
display: true,
text: 'In Play Stats'
},
scale: {
ticks: {
beginAtZero: true
}
}
}
};
window.onload = function() {
window.myRadar = new Chart(document.getElementById('canvas'), config);
};
</script>
</body>
</html>
One way I could think of is creating a function, if all of your charts are similar and only few parameters change, for example in the following example I've considered chartId, labels, dataset and title to be varying. You can also aim to write function that creates datasets given certain parameters:
var randomScalingFactor = function() {
return Math.round(Math.random() * 100);
};
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)'
};
var color = Chart.helpers.color;
var labels = [
['Shots on', ' Target'],
['Shots Off', 'Target'], 'Corners', 'possession (out of 10)'
];
var datasets = [{
label: 'Home team',
backgroundColor: color(window.chartColors.red).alpha(0.2).rgbString(),
borderColor: window.chartColors.red,
pointBackgroundColor: window.chartColors.red,
data: ['5', '7', '4', '6', '2']
}, {
label: 'Away Team',
backgroundColor: color(window.chartColors.blue).alpha(0.2).rgbString(),
borderColor: window.chartColors.blue,
pointBackgroundColor: window.chartColors.blue,
data: ['2', '1', '3', '5', '0']
}];
window.onload = function() {
window.myRadar = createChart('canvas', labels, datasets, 'In Play Stats');
};
function createChart(chartId, labels, dataset, title) {
return new Chart(document.getElementById(chartId), {
type: 'radar',
data: {
labels: labels,
datasets: dataset
},
options: {
legend: {
position: 'top',
},
title: {
display: true,
text: title
},
scale: {
ticks: {
beginAtZero: true
}
}
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<div style="width:40%; min-width: 700px;">
<canvas id="canvas" style="width: 700px;"></canvas>
</div>

How to edit my custom tooltips in my line chart using chart.js?

This is my code
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: [{{ $nDate }}],
datasets: [{
label: 'All Users',
data: [ {{ $nUser }} ],
backgroundColor: ['rgba(54, 162, 235, 0.2)'],
borderColor: ['rgba(54, 162, 235, 1)'],
borderWidth: 3,
lineTension: 0,
labelFontSize : '16',
}]
},
options: {
tooltips: {
mode: 'index',
intersect: false,
position: 'nearest'
},
responsive: false,
legend: { display: false },
scales: {
yAxes: [{
ticks: {
beginAtZero:true,
type: 'category',
labelOffset: 10,
stepSize:250,
callback: function(value, index) {
if (value !== 0) return value;
}
},
gridLines:{
drawBorder:false
}
}],
xAxes: [{
gridLines: {
display: false,
},
}],
},
plugins:{
datalabels:{
display:false
}
}
}
});
My output
My Expected Output
How can I able to put/edit custom tooltip in my line chart? I just want to get the exact tooltips in the second picture but I don't have any idea how to fix it? Another thing is my $nDateI only want to show four dates like 8,15,22,29 But when I tried to create a new array label with value of this [" ", " "]; my chart crashed.
You can use custom callback function to render with your own choice html tags and colors, Follow the official documentation link for further guidance.
http://www.chartjs.org/docs/latest/configuration/tooltip.html#external-custom-tooltips
options: {
tooltips: {
enabled: false,
custom: function(tooltipModel) {}
}
}

Categories

Resources