I am starting to learn the chart.js library.
I drew a pie chart (like “pie”). When you hover over the slices of the diagram, a number appears in the pop-up window that sets the size of the sector.
JavaScript
x
36
36
1
new chart(
2
document.getElementById('diagram_1').getContext('2d'), {
3
type: 'pie',
4
data: {
5
labels: [
6
'Завершенная задача',
7
'Новая задача',
8
'Ошибка выполнения'
9
],
10
datasets: [{
11
label: '# of Votes',
12
data: [@successful_tasks, @new_tasks, @error_tasks],
13
backgroundColor: [
14
'rgba(54, 162, 235, 0.2)',
15
'rgba(255, 206, 86, 0.2)',
16
'rgba(255, 99, 132, 0.2)'
17
],
18
borderColor: [
19
'rgba(54, 162, 235, 1)',
20
'rgba(255, 206, 86, 1)',
21
'rgba(255, 99, 132, 1)'
22
],
23
borderWidth: 1
24
}]
25
},
26
options: {
27
scales: {
28
y: {
29
beginAtZero: true
30
}
31
},
32
responsive: false
33
}
34
}
35
)
36
How can you make this number still displayed at the top, where the sectors are listed (I marked this place with a red circle in the picture)?
I can add the required number to the labels array
JavaScript
1
9
1
2
data: {
3
labels: [
4
'Завершенная задача: ' + @successful_tasks,
5
'Новая задача: ' + @new_tasks,
6
'Ошибка выполнения: ' + @error_tasks
7
],
8
9
But then this number will appear twice in the tooltip
Advertisement
Answer
I found the answer. My project is written in CoffeeScript, but I think it would be more useful for the StackOverflow community to post the code in JS.
JavaScript
1
35
35
1
options: {
2
legend: {
3
labels: {
4
generateLabels: function(chart) {
5
var data = chart.data;
6
if (data.labels.length && data.datasets.length) {
7
return data.labels.map(function(label, i) {
8
var meta = chart.getDatasetMeta(0);
9
var ds = data.datasets[0];
10
var arc = meta.data[i];
11
var custom = arc && arc.custom || {};
12
var getValueAtIndexOrDefault = Chart.helpers.getValueAtIndexOrDefault;
13
var arcOpts = chart.options.elements.arc;
14
var fill = custom.backgroundColor ? custom.backgroundColor : getValueAtIndexOrDefault(ds.backgroundColor, i, arcOpts.backgroundColor);
15
var stroke = custom.borderColor ? custom.borderColor : getValueAtIndexOrDefault(ds.borderColor, i, arcOpts.borderColor);
16
var bw = custom.borderWidth ? custom.borderWidth : getValueAtIndexOrDefault(ds.borderWidth, i, arcOpts.borderWidth);
17
var value = chart.config.data.datasets[arc._datasetIndex].data[arc._index];
18
19
return {
20
text: label + ": " + value,
21
fillStyle: fill,
22
strokeStyle: stroke,
23
lineWidth: bw,
24
hidden: isNaN(ds.data[i]) || meta.data[i].hidden,
25
index: i
26
};
27
});
28
} else {
29
return [];
30
}
31
}
32
}
33
}
34
}
35