I am having difficulty adding a label to points on my bubble graph.
I am trying to assign the same label as the legend for each of my datasets.
I have tried to assign these points a label, but I seem to only be able to display it's value.
I would like to display the value of the point above and a custom label below the point (Like in the second image below).
Here is the code for my progress so far on the chart.
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bubble',
data: {
datasets: [
{
label: 'Top',
data: [
{x: 110, y: 0, r: 10, name: "Performance"}
],
backgroundColor: "rgba(153,255,51,0.6)"
},
{
label: 'Average',
data: [
{x: 75, y: 0, r: 10, name: "Performance"}
],
backgroundColor: "rgba(153,255,51,0.6)"
},
{
label: 'You 2017',
data: [
{x: 55, y: 0, r: 10, name: "Performance"}
],
backgroundColor: "rgba(153,255,51,0.6)"
},
{
label: 'You 2018',
data: [
{x: 90, y: 0, r: 10, name: "Performance"} // The labe needs to be
],
backgroundColor: "rgba(255,0,128,0.6)"
}
]
},
pointDot : true,
options: {
plugins: {
datalabels: {
anchor: function (context) {
var value = context.dataset.data[context.dataIndex];
return value.x < 1000 ? 'end' : 'center';
},
align: function (context) {
var value = context.dataset.data[context.dataIndex];
return value.x < 1000 ? 'end' : 'center';
},
color: function (context) {
var value = context.dataset.data[context.dataIndex];
return value.x < 1000 ? context.dataset.backgroundColor : 'white';
},
font: {
weight: 'bold'
},
formatter: function (value) {
return Math.round(value.x);
},
offset: 2,
padding: 0
}
},
maintainAspectRatio: false,
scales: {
yAxes: [{
id: 'first-y-axis',
type: 'linear',
ticks: {
min: 0,
max: 1,
stepSize: 1,
display: false
},
gridLines: {
display: false,
drawBorder: false
}
}],
xAxes: [
{
id: 'first-x-axis',
ticks: {
min: 50, // Controls where axis starts
max: 120, // Controls where axis finishes
stepSize: 70 // Control the gap between the first x-axis value and the last x-axis value
},
gridLines: {
display: false,
lineWidth: 3 // Width of bottom line
}
}
]
}
}
});
</script>
I appreciate any help or suggestions ^_^
Modify your datalabels plugin configuration this way:
datalabels: {
anchor: function (context) {
var value = context.dataset.data[context.dataIndex];
return value.x < 1000 ? 'end' : 'center';
},
align: function (context) {
var value = context.dataset.data[context.dataIndex];
return value.x < 1000 ? 'end' : 'center';
},
color: function (context) {
var value = context.dataset.data[context.dataIndex];
return value.x < 1000 ? context.dataset.backgroundColor : 'white';
},
font: {
weight: 'bold'
},
formatter: function (value, context) {
return context.dataset.label;
},
offset: 2,
padding: 0
}
The formatter has also a context
parameter which contains info about dataset like label.
Here is a fiddle: https://jsfiddle.net/beaver71/3ed8t6pe/