borderdash options in chart js changes my legend - chart.js

I added borderdash to my chart to make make the line more distinct but it alter the shape of my legend. I want it to be an square, not that weird rectangle shape in the legend. I have no idea how to fix this. Does anyone know of an solution to this?
Here is my chart js options:
var options = {
responsive: true,
maintainAspectRatio: false,
backgroundColor: "#fffffff",
title: {
display: true,
text: title,
fontSize: 24
},
legend: {
display: true
},
tooltips: {
callbacks: {
label: function(tooltipItem, ctx) {
var label;
if(x_axis == "Temperature [K]")
{
label = [["Pressure: " + tooltipItem.yLabel], ["Temperature: " + tooltipItem.xLabel]];
}
else
{
label = [["Pressure: " + tooltipItem.yLabel], ["Abundance: " + tooltipItem.xLabel]];
}
return label;
},
}
},
animation: {
duration: 1 // general animation time
},
scales: {
xAxes: [{
type: x_type,
display: true,
ticks: {
beginAtZero: false,
autoSkip: false,
fontSize: 20,
suggestedMin: x_min,
suggestddMax: x_max,
callback: function(value, index, values) {
if (x_axis == "Abundance"){
if (value == 1e-9)
{
return 1 + "n";
}
else if(value == 1e-8)
{
return 10 + "n";
}
else if(value == 1e-7)
{
return 100 + "n";
}
else if (value == 1e-6){
return 1 + "\u03BC";
}
else if (value == 1e-5)
{
return 10 + "\u03BC";
}
else if(value == 1e-4)
{
return 100 + "\u03BC";
}
else if (value == .001 || value == .01 || value == .1 || value == 1){
return value;
}
}
else if (x_axis == "Temperature [K]")
{
return value;
}
}
},
scaleLabel: {
labelString: x_axis,
display: true,
fontSize: 20,
fontColor: "Black",
}
}],
yAxes: [{
type: 'logarithmic',
display: true,
ticks: {
reverse: true,
beginAtZero: false,
autoSkip: false,
min: 1e-6,
max: 1,
steps: 6,
fontSize: 20,
callback: function(value, index, values) {
// y_log_ticks = [1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1]
if (value == 1e-6){
return 1 + "\u03BC";
}
else if (value == 1e-5)
{
return 10 + "\u03BC";
}
else if(value == 1e-4)
{
return 100 + "\u03BC";
}
else if (value == .001 || value == .01 || value == .1 || value == 1){
return value;
}
}
},
scaleLabel:{
display: true,
labelString: y_axis,
diplay: true,
fontSize: 20,
fontColor: "Black"}
}]
}
}
And here is how I am adding the data with the borderdash:
function update_plot(json){
line_patter = [[1,1], [10, 10], [20, 5], [15, 3, 3, 3], [20, 3, 3, 3, 3, 3, 3, 3], [12, 3, 3]];
counter++;
chart1.data.datasets.unshift({
data: json.temp_pressure,
showLine: true,
pointRadius: 5,
fill: false,
label: "Plot " + counter,
borderDash: line_patter[counter % 6],
borderColor: getLineColor(chart1.data.datasets.length),
backgroundColor: getLineColor(chart1.data.datasets.length),
});
chart2.data.datasets.unshift({
data: json.fh2o,
showLine: true,
pointRadius: 5,
fill: false,
label: "Plot " + counter + ": H2O",
borderDash: line_patter[counter % 6],
borderColor: getLineColor(chart2.data.datasets.length),
backgroundColor: getLineColor(chart2.data.datasets.length),
});
chart2.data.datasets.unshift({
data: json.fo3,
showLine: true,
pointRadius: 5,
fill: false,
label: "Plot " + counter + ": O3",
borderDash: line_patter[counter % 6],
borderColor: getLineColor(chart2.data.datasets.length),
backgroundColor: getLineColor(chart2.data.datasets.length),
});
chart1.update();
chart2.update();
}

You need to provide your own Legend Label Configuration by defining legend.labels.generateLabels inside chart options.
In the following code sample, generateLabels creates an array of objects that implement the Legend Item Interface. Each object simply takes its properties from the corresponding dataset but leaves lineDash undefined.
new Chart(document.getElementById('myChartAxis'), {
type: 'line',
data: {
labels: ['A', 'B', 'C', 'D'],
datasets: [
{
label: 'WARNINGS',
data: [0, 2, 3, 2],
borderDash: [5],
borderColor: 'rgb(255, 159, 64)',
backgroundColor: 'rgba(255, 159, 64, 0.2)',
fill: false
},
{
label: 'ERRORS',
data: [1, 1, 4, 3],
borderDash: [2],
borderColor: 'rgb(255, 99, 132)',
backgroundColor: 'rgba(255, 99, 132, 0.2)',
fill: false
}
]
},
options: {
legend: {
labels: {
generateLabels: chart => chart.data.datasets.map((dataset, i) => ({
datasetIndex: i,
text: dataset.label,
fillStyle: dataset.backgroundColor,
strokeStyle: dataset.borderColor
}))
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js"></script>
<canvas id="myChartAxis" height="90"></canvas>

Related

Display Datalabel for an specific point in Chart Js

I'm trying to build a chart.js Line and with scatter points and I would like to have the datalabel to show just on the scatter points, I've tried to do it with datalabels plugin from chart js but it shows the datalabel for all datasets including the line, How can I show just the specific scatter points? this is what the code looks like:
Chart.register(ChartDataLabels);
fetch('https://raw.githubusercontent.com/ConeDigital/assets/main/data.json')
.then(response => response.json())
.then(data => {
var ctx = document.getElementById('myChart2').getContext('2d'),
chart = new Chart(ctx, {
type: 'line',
data: getChartData(data),
options: {
legend: {
display: false
},
plugins: {
datalabels: { // This code is used to display data values
anchor: 'end',
align: 'top',
font: {
weight: 'bold',
size: 16
}
}
},
tooltips: {
mode: 'index',
intersect: false,
callbacks: {
label: function (tooltipItem, data) {
return data.datasets[tooltipItem.datasetIndex].label + ': ' + tooltipItem.yLabel+"%";
},
labelColor: function (tooltipItem, chart) {
let border = ''
let background = ''
let colors
if ( tooltipItem.datasetIndex === 1 ) {
colors = {
borderColor: '#fff',
backgroundColor: '#001F5B'
}
} else {
colors = {
borderColor: '#fff',
backgroundColor: '#eb8484'
}
}
return colors
}
}
},
responsive: true,
scales: {
xAxes: [{
stacked: false,
scaleLabel: {
display: false,
labelString: 'Datum'
},
ticks: {
display: false
},
gridLines: {
display: false,
drawBorder: false,
}
}],
yAxes: [{
stacked: false,
ticks: {
display: false
},
gridLines: {
display: false,
drawBorder: false
},
scaleLabel: {
display: false,
labelString: 'Procent'
}
}]
}
}
});
})
function getChartData(json) {
var labels = [];
var omx_dataset = {
label: 'OMXS30',
borderColor: '#eb8484',
fill: false,
pointRadius: 0,
borderWidth: 1,
data: []
};
var gadd_dataset = {
label: "GADD SMP SEK",
borderColor: '#001F5B',
fill: false,
pointRadius: 0,
borderWidth: 1,
data: []
};
var mark1_dataset = {
label: 'Start',
borderWidth: 2,
borderColor: '#FF0000',
fill: false,
type: 'scatter',
data: [{
x: '2011-03-29',
y: 0
}],
pointRadius: 12
};
var mark2_dataset = {
label: '2016',
borderWidth: 2,
borderColor: '#FF0000',
fill: false,
type: 'scatter',
data: [{
x: '2015-12-31',
y: 20
}],
pointRadius: 12
};
var mark3_dataset = {
label: '2020',
borderWidth: 2,
borderColor: '#FF0000',
fill: false,
type: 'scatter',
data: [{
x: '2020-01-07',
y: 59
}],
pointRadius: 12
};
var mark4_dataset = {
label: '2022',
borderWidth: 2,
borderColor: '#FF0000',
fill: false,
type: 'scatter',
data: [{
x: '2022-01-03',
y: 109
}],
pointRadius: 12
};
json.map((point,i) => {
labels.push(point.Date)
const gadd_num = (point['GADD SMP SEK']*100).toFixed(2)
const omx_num = (point['OMXS30']*100).toFixed(2)
gadd_dataset.data.push(gadd_num)
omx_dataset.data.push(omx_num)
//console.log(point.Date)
//result1_dataset.data.push(point.date)
})
return {
labels: labels,
datasets: [omx_dataset, gadd_dataset, mark1_dataset, mark2_dataset, mark3_dataset, mark4_dataset]
}
}
Right now it shows all the datalabels from all the datasets and it looks messed up,
Thanks in advance
You could add the datalabels config to the line datasets, disabling the plugin, as the following:
var omx_dataset = {
label: 'OMXS30',
borderColor: '#eb8484',
fill: false,
pointRadius: 0,
borderWidth: 1,
data: []
datalabels: {
display: false
}
};
var gadd_dataset = {
label: "GADD SMP SEK",
borderColor: '#001F5B',
fill: false,
pointRadius: 0,
borderWidth: 1,
data: [],
datalabels: {
display: false
}
};

Chartjs y axes label overflow

We are using react chart js but the problem occurs when we try to show multi-line charts in small widgets with high y-axis values.
Overflow occurs in smaller widths and large y axes numbers. I already try a thousand suffixes but it doesn't work. Is it possible to keep the y-axis constant by making the x-axis smaller? Or handle it responsive.
function randomTwoNumbers(n1, n2) {
return Math.floor(Math.random() * (n2 - n1 + 1) + n1)
}
function generateData(count) {
let data = []
for (let index = 0; index < count; index++) {
data.push({
x: `2022-07-${index}T00:00:00.000Z`,
y: randomTwoNumbers(1000000, 9999999)
})
}
return data
}
const data = {
datasets: [
{
data: generateData(100),
label: 'Temperature',
borderColor: '#236EF1',
tension: 0.5,
pointRadius: 1,
pointHoverRadius: 5,
pointHitRadius: 20,
yAxisID: 'y0'
},
{
data: generateData(100),
label: 'Humidity',
borderColor: '#CA840C',
tension: 0.5,
pointRadius: 1,
pointHoverRadius: 5,
pointHitRadius: 20,
yAxisID: 'y1'
}
]
}
const options = {
responsive: true,
resizeDelay: 300,
scales: {
x: {
display: true,
grid: {
borderColor: '#5E646E',
tickColor: '#5E646E',
display: true,
drawOnChartArea: false
},
ticks: {
autoSkip: false,
maxRotation: 0,
font: {
size: 10,
family: 'Inter',
lineHeight: '12px',
weight: '500'
}
},
time: {
unit: 'day',
displayFormats: {
minute: 'p',
hour: 'p',
day: 'MMM, do'
}
},
type: 'time',
offset: true,
adapters: {
date: {
locale: {
code: 'en-US',
formatLong: {},
localize: {},
match: {}
}
}
}
},
y0: {
display: true,
grid: {
borderColor: '#5E646E',
tickColor: '#5E646E',
display: true,
drawOnChartArea: false
},
ticks: {
font: {
size: 10,
family: 'Inter',
lineHeight: '12px',
weight: '500'
}
},
stack: 'single',
offset: false
},
y1: {
display: true,
grid: {
borderColor: '#5E646E',
tickColor: '#5E646E',
display: true,
drawOnChartArea: false
},
ticks: {
font: {
size: 10,
family: 'Inter',
lineHeight: '12px',
weight: '500'
}
},
stack: 'single',
offset: false
}
},
maintainAspectRatio: false,
plugins: {
legend: {
display: false
},
title: {
display: false
},
tooltip: {
displayColors: false
}
}
}
var config = {
type: 'line',
data,
options
}
var ctx = document.getElementById('canvas').getContext('2d')
window.myLine = new Chart(ctx, config)
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.2/chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-adapter-moment/1.0.1/chartjs-adapter-moment.min.js"></script>
<div style="width: 200px">
<canvas id="canvas"></canvas>
</div>

Always show last tooltip on all datasets, leave the rest to display on hover? ChartJS

I'm a little stuck on how I would achieve this since it's a little unorthodox in relation to what the plugin does.
I'm attempting for each dataset to keep the last tooltip open at all times and leave the rest to be displayed on hover.
Currently, I'm using this to keep them all displayed:
Chart.plugins.register({
beforeRender: function (chart) {
if (chart.config.options.showAllTooltips) {
chart.pluginTooltips = [];
chart.config.data.datasets.forEach(function (dataset, i) {
console.log(chart);
chart.getDatasetMeta(i).data.forEach(function (sector, j) {
console.log(sector);
chart.pluginTooltips.push(new Chart.Tooltip({
_chart: chart.chart,
_chartInstance: chart,
_data: chart.data,
_options: chart.options.tooltips,
_active: [sector]
}, chart));
});
});
chart.options.tooltips.enabled = false;
}
},
afterDraw: function (chart, easing) {
if (chart.config.options.showAllTooltips) {
if (!chart.allTooltipsOnce) {
if (easing !== 1) {
return;
}
chart.allTooltipsOnce = true;
}
chart.options.tooltips.enabled = true;
Chart.helpers.each(chart.pluginTooltips, function (tooltip) {
tooltip.initialize();
tooltip.update();
tooltip.pivot();
tooltip.transition(easing).draw();
});
chart.options.tooltips.enabled = false;
}
}
});
Is there a way to only do this for the last tooltip in each dataset?
I've come across a way to hide tooltips:
filter: function (tooltipItem, data) {
var label = data.labels[tooltipItem.index];
if (label === labels[labels.length - 1]) {
console.log(tooltipItem);
} else {
return true;
}
}
But this just doesn't display them whatsoever since it's returning false.
Ultimately it will look like this, with the other tooltips displaying on hover of the corresponding node:
Any help greatly appreciated.
I would try to use chartjs-plugin-datalabels for such task.
You can try it out directly on their pages - scriptable interactions
setup
Setting some random data:
var DATA_COUNT = 8;
var labels = [];
Utils.srand(100);
for (var i = 0; i < DATA_COUNT; ++i) {
labels.push('' + i);
}
var DATA_COUNT = 8;
var labels = [];
Utils.srand(100);
for (var i = 0; i < DATA_COUNT; ++i) {
labels.push('' + i);
}
config
Here I did some changes
{
type: 'line',
data: {
labels: labels,
datasets: [{
label: 'France',
backgroundColor: Utils.color(0),
borderColor: Utils.color(0),
data: Utils.numbers({
count: DATA_COUNT,
min: 10,
max: 100
}),
datalabels: {
align: function(context) {
return context.active ? 'start' : 'center';
}
}
}, {
label: 'Canada',
backgroundColor: Utils.color(1),
borderColor: Utils.color(1),
data: Utils.numbers({
count: DATA_COUNT,
min: 0,
max: 100
})
}, {
label: 'USA',
backgroundColor: Utils.color(2),
borderColor: Utils.color(2),
data: Utils.numbers({
count: DATA_COUNT,
min: 0,
max: 100
}),
datalabels: {
align: function(context) {
return context.active ? 'end' : 'center';
}
}
}]
},
options: {
plugins: {
datalabels: {
backgroundColor: function(context) {
return context.active ? context.dataset.backgroundColor : 'white';
},
borderColor: function(context) {
return context.dataset.backgroundColor;
},
borderRadius: function(context) {
return context.active ? 0 : 1;
},
borderWidth: 1,
color: function(context) {
return context.active ? 'white' : context.dataset.backgroundColor;
},
font: {
weight: 'bold'
},
formatter: function(value, context) {
value = Math.round(value * 100) / 100;
if (context.dataIndex === context.dataset.data.length - 1) {
return context.dataset.label + '\n' + value + '%';
} else {
return context.active
? context.dataset.label + '\n' + value + '%'
: ''
}
},
offset: 8,
padding: 0,
textAlign: 'center'
}
},
// Core options
aspectRatio: 5 / 3,
layout: {
padding: {
bottom: 16,
right: 40,
left: 8,
top: 40
}
},
hover: {
mode: 'index',
intersect: false
},
elements: {
line: {
fill: false
}
},
scales: {
yAxes: [{
stacked: true
}]
}
}
}
The main part here is:
formatter: function(value, context) {
value = Math.round(value * 100) / 100;
if (context.dataIndex === context.dataset.data.length - 1) {
return context.dataset.label + '\n' + value + '%';
} else {
return context.active
? context.dataset.label + '\n' + value + '%'
: ''
}
},
The formatter: where I show the label permanently only for context.dataIndex === context.dataset.data.length - 1.
In other cases if it is inactive I show only empty box in other case (hover) I show the information.
How does it look?
No hover
Hover with mouse
So this is the entire hmtl file with all relevant code. As I said, I am no programmer. This effort is from loads of trial and error, including several bits of code from stackoverflow questions.
<script>
$(document).ready(function () {
showtempGraph();
});
function showtempGraph()
{
{
$.post("temperaturedata.php",
function (data)
{
console.log(data);
var temptime = [];
var temp = [];
for (var i in data) {
temptime.push(data[i].timestamp);
temp.push(data[i].temperature);
}
var tempmin = Math.min(...temp);
var tempmax = Math.max(...temp);
var charttempdata = {
labels: temptime,
datasets: [
{
label: 'Temperatur',
pointRadius: 3,
backgroundColor: 'rgba(26, 137, 245, 0.2)',
borderColor: 'rgba(26, 137, 245, 1)',
hoverBackgroundColor: 'rgba(255, 255, 255, 1)',
hoverBorderColor: 'rgba(255, 255, 255, 1)',
pointBackgroundColor: 'rgba(12, 68, 122, 1)',
pointHoverBorderColor: "rgba(255, 255, 255, 0.8)",
data: temp
}
]
};
var graphtempTarget = $("#tempgraphCanvas");
var linetempGraph = new Chart(graphtempTarget, {
type: 'line',
data: charttempdata,
options: {
maintainAspectRatio: false,
tooltips: {
enabled: true,
custom: function(tooltip) {
if (!tooltip) return;
tooltip.displayColors = false;
},
callbacks: {
title: function(tooltipItems, tempdata) {
return 'Klokken: ' + tooltipItems[0].xLabel;
},
label: function(tooltipItem, tempdata) {
return 'Temperatur: ' + Number(tooltipItem.yLabel).toFixed(2) + '°C';
}
}
},
legend: {
display: false,
},
responsive: true,
scales: {
xAxes: [{
type: 'time',
time: {
displayFormats: {
hour: 'HH:mm'
},
tooltipFormat: 'HH:mm',
},
unit : 'day',
gridLines: {
color: '#999999',
lineWidth: 1
},
ticks: {
fontColor: "#fff",
}
}],
yAxes: [
{
type: 'linear',
position: 'left',
gridLines: {
color: '#999999',
lineWidth: 1
},
ticks: {
fontColor: "#fff",
}
}, {
type: 'linear',
position: "right",
afterUpdate: function(scaleInstance) {
console.dir(scaleInstance);
},
gridLines: {
color: '#999999)',
lineWidth: 0.5
},
ticks: {
stepSize: tempmax - tempmin,
min: tempmin,
max: tempmax,
mirror: true,
padding: -10,
fontColor: "#fff",
fontSize: 18,
callback: function(value) {
return value + '°C';
}
},
scaleLabel: {
display: true,
labelString: '°C',
fontColor: "#fff",
fontSize: 14
}
}]
},
}
});
});
}
}
</script>

Custom scatter chart extended from scatter chart becomes line chart

I'm unable to find an explanation so as why my customized scatter charts display a line chart instead.
I've created this custom chart by extending it from scatter using the basic :
Chart.defaults.scatterCustom = Chart.defaults.scatter;
Chart.controllers.scatterCustom = Chart.controllers.scatter.extend({ ...
Following is the entire code i'm using and a fiddle to illustrate my problem.
We can see the 3 differents charts, 2 are default scatter and one is customScatter.
The draw function was added later, thinking it would bring back the normal behaviour but it doesn't change anything.
Any help greatly appreciated!
tidechart = {
tideChart: "",
initTidechart: function() {
Chart.defaults.scatterCustom = Chart.defaults.scatter;
Chart.controllers.scatterCustom = Chart.controllers.scatter.extend({
draw: function(ease) {
Chart.controllers.scatter.prototype.draw.call(this, ease);
},
fireSliderEvent: function(point, canvas, boundingRect) {
var mouseX = Math.round((boundingRect.left + point._view.x) / (boundingRect.right - boundingRect.left) * canvas.width / this.chart.chart.currentDevicePixelRatio);
var mouseY = Math.round((boundingRect.top + point._view.y) / (boundingRect.bottom - boundingRect.top) * canvas.height / this.chart.chart.currentDevicePixelRatio);
var oEvent = document.createEvent('MouseEvents');
oEvent.initMouseEvent('click', true, true, document.defaultView,
0, mouseX, mouseY, mouseX, mouseY,
false, false, false, false, 0, canvas);
canvas.dispatchEvent(oEvent);
},
highlightPointsByIndex: function(datasetIndex, index) {
var canvas = this.chart.canvas;
var boundingRect = canvas.getBoundingClientRect();
var points = this.chart.getDatasetMeta(datasetIndex).data;
this.fireSliderEvent(points[index], canvas, boundingRect);
},
highlightPointsByValue: function(points, value) {
var dataPoints = this._data;
for (var index = 0; index < dataPoints.length; ++index) {
if (dataPoints[index].toString() === value.toString()) {
this.highlightPointsByIndex(points, index);
break;
}
}
}
});
tideChartOptions = {
maintainAspectRatio: false,
legend: {
display: true
},
tooltips: {
backgroundColor: '#f5f5f5',
titleFontColor: '#333',
bodyFontColor: '#666',
bodySpacing: 4,
xPadding: 12,
mode: "nearest",
intersect: 0,
position: "nearest",
filter: function(tooltipItem) {
return tooltipItem.datasetIndex != 0;
}
},
responsive: true,
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: 'Tide level'
},
gridLines: {
drawBorder: false,
color: 'rgba(29,140,248,0.0)',
zeroLineColor: "transparent",
},
ticks: {
suggestedMin: 0,
suggestedMax: 10,
padding: 20,
fontColor: "#9a9a9a"
},
afterTickToLabelConversion: function(q) {
for (var tick in q.ticks) {
q.ticks[tick] += ' m';
}
},
}],
xAxes: [{
display: true,
type: 'time',
time: {
parser: 'YYYY-MM-DD HH:mm:ss',
tooltipFormat: 'll HH:mm',
unit: 'day',
unitStepSize: 1,
displayFormats: {
'month': 'MMM DD'
}
},
gridLines: {
drawBorder: false,
color: 'rgba(225,78,202,0.1)',
zeroLineColor: "transparent",
},
ticks: {
padding: 20,
fontColor: "#9a9a9a"
}
}]
}
};
var data = {
labels: ['01/01/2020','01/02/2020','01/03/2020','01/04/2020'],
datasets: [
{
label: 'Camera 1',
type: 'scatter',
fill: false,
backgroundColor: '#2DAAE1',
borderColor: '#2DAAE1',
borderWidth: 0,
pointBackgroundColor: '#2DAAE1',
pointHoverBackgroundColor: '#2DAAE1',
pointBorderWidth: 0,
pointHoverRadius: 5,
pointRadius: 2,
data: [1,5,6,7]
},
{
fill: false,
type: 'scatter',
label: 'Camera 2',
backgroundColor: '#FFC329',
borderColor: '#FFC329',
borderWidth: 2,
borderDash: [],
borderDashOffset: 0.0,
pointBackgroundColor: '#FFC329',
pointHoverBackgroundColor: '#FFC329',
pointBorderWidth: 0,
pointHoverRadius: 5,
pointRadius: 2,
data: [3,2,8,1]
},
{
fill: false,
type: 'scatterCustom',
label: 'Camera 3',
backgroundColor: '#FF5229',
borderColor: '#FF5229',
borderWidth: 2,
borderDash: [],
borderDashOffset: 0.0,
pointBackgroundColor: '#FF5229',
pointHoverBackgroundColor: '#FF5229',
pointBorderWidth: 0,
pointHoverRadius: 5,
pointRadius: 2,
data: [8,4,5,3]
}
]
};
//tidechart.tideChart = new Chart(ctx, config);
tidechart.tideChart = new Chart($("#tidechart"), {
data: data,
options: tideChartOptions
});
}
}
tidechart.initTidechart();
This solves it
Chart.defaults.global.datasets.scatterCustom = Chart.defaults.global.datasets.scatter;

How can I datalabels and Sum display in the same time on a stacked bar

I try to have in the same time datalabels and the sum display in my stacked bar chart.
I use chartjs-plugin-datalabels.js to display datalabels or sum.
Above just with datalabels:
Above just with sum :
I would like to have both in the same chart.
I use the follow tricks to sum display :
<script>
const totalizer = {
id: 'totalizer',
beforeUpdate: chart => {
let totals = {}
let utmost = 0
chart.data.datasets.forEach((dataset, datasetIndex) => {
if (chart.isDatasetVisible(datasetIndex)) {
utmost = datasetIndex
dataset.data.forEach((value, index) => {
totals[index] = (totals[index] || 0) + value
})
}
})
chart.$totalizer = {
totals: totals,
utmost: utmost
}
}
}
new Chart('chart', {
type: 'bar',
data: {
labels: ["Note par thème du répondant", "Note par thème sectorielle", "Note par thème générale"],
datasets: [{
label: 'Thème 1',
data: [12, 19, 3],
backgroundColor: 'rgba(255, 206, 86)'
},
{
label: 'Thème 2',
data: [3,8,1],
backgroundColor: 'rgba(54, 162, 235)'
},
{
label: 'Thème 3',
data: [ 5, 2, 3],
backgroundColor: 'rgba(255, 255, 132)'
},{
label: 'Thème 4',
data: [ 5, 2, 3],
backgroundColor: 'rgba(255, 99, 255)'
},{
label: 'Thème 5',
data: [ 5, 2, 3],
backgroundColor: 'rgba(100, 250, 132)'
},{
label: 'Thème 6',
data: [ 5, 2, 3],
backgroundColor: 'rgba(89, 99, 132)'
},{
label: 'Thème 7',
data: [ 5, 2, 3],
backgroundColor: 'rgba(255, 0, 132)'
},{
label: 'Thème 8',
data: [ 5, 2, 3],
backgroundColor: 'rgba(0, 150, 255)'
},{
label: 'Thème 9',
data: [ 5, 2, 3],
backgroundColor: 'rgba(100, 100, 100)'
},{
label: 'Thème 10',
data: [ 10, 4, 7],
backgroundColor: 'rgba(255, 255, 0)'
}]
},
options: {
title :{
display :true,
text : "Mon titre"
},
scales: {
yAxes: [{
stacked: true,
ticks: {
beginAtZero: true,
suggestedMax: 100
}
}],
xAxes: [{
stacked: true
}]
},
plugins: {
datalabels: {
formatter: (value, ctx) => {
const total = ctx.chart.$totalizer.totals[ctx.dataIndex]
return total.toLocaleString('fr-FR', {})
},
align: 'end',
anchor: 'end',
display: function(ctx) {
return ctx.datasetIndex === ctx.chart.$totalizer.utmost
}
}
}
},
plugins: [totalizer]
});
</script>
I would appreciate any help. Thanks!
OK, I found a way to show Sum and datalabels in the same time.
I add new dataset to represent "Total data" with a backgroundColor transparent and I add this following code in my dataset Total:
datalabels: {
backgroundColor: function (context) {
return 'rgba(244,50,49)';
},
formatter: (value, ctx) => {
const total = ctx.chart.$totalizer.totals[ctx.dataIndex];
return total.toLocaleString('fr-FR', {})
},
align: 'end',
anchor: 'end',
display: function (ctx) {
return ctx.datasetIndex === ctx.chart.$totalizer.utmost
}
Full code bellow :
<script>
const totalizer = {
id: 'totalizer',
beforeUpdate: chart => {
let totals = {}
let utmost = 0
chart.data.datasets.forEach((dataset, datasetIndex) => {
if (chart.isDatasetVisible(datasetIndex)) {
utmost = datasetIndex
dataset.data.forEach((value, index) => {
totals[index] = (totals[index] || 0) + value
})
}
})
chart.$totalizer = {
totals: totals,
utmost: utmost
}
}
}
new Chart('chart', {
type: 'bar',
data: {
labels: ["Note par thème du répondant", "Note par thème sectorielle", "Note par thème générale"],
datasets: [{
label: 'Thème 1',
data: [10, 10, 10],
backgroundColor: 'rgba(68,114,196,0.6)'
}, {
label: 'Thème 2',
data: [13, 8, 11],
backgroundColor: 'rgba(237,125,49,0.6)'
}, {
label: 'Thème 3',
data: [5, 12, 13],
backgroundColor: 'rgba(165,165,165,0.6)'
}, {
label: 'Thème 4',
data: [9, 12, 13],
backgroundColor: 'rgba(255,192,0,0.6)'
}, {
label: 'Thème 5',
data: [5, 12, 9],
backgroundColor: 'rgba(91,155,213,0.6)'
}, {
label: 'Thème 6',
data: [9, 12, 5],
backgroundColor: 'rgba(112,173,71,0.6)'
}, {
label: 'Thème 7',
data: [5, 12, 10],
backgroundColor: 'rgba(38,68,120,0.6)'
}, {
label: 'Thème 8',
data: [15, 12, 10],
backgroundColor: 'rgba(99,99,99,0.6)'
}, {
label: 'Thème 9',
data: [15, 12, 11],
backgroundColor: 'rgba(37,94,145,0.6)'
}, {
label: 'Thème 10',
data: [10, 4, 7],
backgroundColor: 'rgba(24,91,62,0.6)'
}, {
label: 'Total',
data: [0, 0, 0],
backgroundColor: 'rgba(24,91,62,0)',
datalabels: {
backgroundColor: function (context) {
return 'rgba(244,50,49)';
},
formatter: (value, ctx) => {
const total = ctx.chart.$totalizer.totals[ctx.dataIndex];
return total.toLocaleString('fr-FR', {})
},
align: 'end',
anchor: 'end',
display: function (ctx) {
return ctx.datasetIndex === ctx.chart.$totalizer.utmost
}
}
}
]
},
options: {
title: {
text: "Mon titre",
display: true
},
scales: {
yAxes: [{
stacked: true,
ticks: {
beginAtZero: true,
suggestedMax: 100
}
}
],
xAxes: [{
stacked: true
}
]
},
plugins: {
datalabels: {
color: 'rgba(255,255,255)',
display: function (context) {
return context.chart.isDatasetVisible(context.datasetIndex);
},
backgroundColor: function (context) {
return context.dataset.backgroundColor;
},
borderRadius: 4,
font: {
weight: 'bold'
}
}
}
},
plugins: [totalizer]
});
</script>
Great! I just simplified solution without totilizer:
datasets: {
label: 'Total',
data: [120, 120, 120, 120, 120, 120, 120, 120, 120, 120],
backgroundColor: 'rgba(24,91,62,0)',
datalabels: {
backgroundColor: () => 'white',
formatter: (value, ctx) => {
let total = 0;
let index = ctx.dataIndex;
data.datasets.map((d, i) => {
if (i === 2) return;
total += d.data[index];
});
return total;
},
align: 'end',
anchor: 'end',
padding: 0,
},
},