Chart.JS tooltip callbacks label and title (v3.5) - javascript

(Please note: There are lots of answers for v2, this is for v3)
I'm trying to setup tooltips label and title for a doughnut chart.
Code:
//Create the donut chart
donut = new Chart('questions_positivity_donut', {
type: 'doughnut',
data: {
labels: ["Positive", "Other"],
datasets: [{
label: 'Sentiment',
data: [user_context.state.avg_joy, (1-user_context.state.avg_joy)],
backgroundColor: ['#a9a9a9','#f2f2f2']
}]
},
options: {
cutout: "70%",
plugins: {
legend: {
display: false
},
maintainAspectRatio: false,
responsive: true,
tooltip: {
callbacks: {
label: function(context) {
let label = new Intl.NumberFormat('en-US', {style: 'percent', minimumFractionDigits: 0, maximumFractionDigits: 0}).format(context.formattedValue);
return label;
},
title: function(context) {
let title = context.parsed.x;
return title;
}
},
displayColors: false
}
}
}
});
The label now works, and displays the value of the data, but the title is returning blank, instead of returning the label of the data ("Positive" or "Other").
How can I return the correct title in the tooltip.callback?
Example: "Positive 35%" and "Other 65%"

If you log the context you could see its an array containing objects, with the default interaction mode you are using it only contains a single item so you can select that one and then access the label attribute on it like so:
var options = {
type: 'doughnut',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
}]
},
options: {
plugins: {
tooltip: {
callbacks: {
label: function(context) {
let label = new Intl.NumberFormat('en-US', {
style: 'percent',
minimumFractionDigits: 0,
maximumFractionDigits: 0
}).format(context.formattedValue);
return label;
},
title: function(context) {
let title = context[0].label;
return title;
}
},
}
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.js"></script>
</body>

Related

How to change React line chart tooltip title font family in chart.js

I am using "chart.js": "^3.7.1", along with react-chartjs-2 in react web app. I want to change the chart tooltip font family. Here is the options i am using in the chart. I am unable to apply font family to the line chart. i want to apply a custom font for the title in the tooltip. i have used props mentioned in the documentation of chart js
const options = {
animation,
plugins: {
tooltip: {
backgroundColor: "#fff",
displayColors: false,
borderColor: "#8b7a7a",
borderWidth: 0.5,
bodyColor: "#0000",
titleColor: "#8b7a7a",
// bodyFontColor: "#8b7a7a",
padding: 10,
footerSpacing: 0,
boxHeight: 10,
title: {
font: {
size: 50,
family: "'Work Sans',sans-serif",
},
},
callbacks: {
title: function (t, d) {
let datae = moment(t[0].label).format("MMM DD, YYYY");
const aa = t[0].dataset.label;
const val = t[0].formattedValue;
return `Date: ${datae.toString()}\n${aa}: ${val}`;
},
},
},
legend: {
display: false,
},
},
elements: {
line: {
tension: 0,
},
},
legend: {
display: false,
},
scales: {
x: {
grid: {
display: false,
},
},
y: {
grid: {
display: false,
},
},
},
};
As can be read here you need to configure the font for the tooltip title in the titleFont property and not in the title.font property:
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'orange'
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderColor: 'pink'
}
]
},
options: {
plugins: {
tooltip: {
titleFont: {
family: 'commic-sans-ms'
}
}
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.js"></script>
</body>
you can change the style of tooltip in the chart.js, in the options property of chart. Inside options you need to access tooltip inside of plugins object, so first you have to create it, then create tooltip object inside it. Now, you can change some features of tooltip according to the this link.
for example:
plugins: {
tooltip: {
titleFont: { size: 13.2, family: "Yekan" },
bodyFont: { size: 14.2, family: "Yekan" },
callbacks: {
// to change the label context
label: function (context) {
var label = context.parsed.y;
return label;
},
},
},
}

Chart.js v3 - beginAtZero does nothing to my chart

I read many threads on the beginAtZero parameter in Chart.js, but none of the solutions I found actually work for me.
I have a simple line chart with dates on my x axe and integers in my y axe. I can't manage to make my y axe start with 0.
let atchoum = document.querySelector("#atchoum")
let statchoum = new Chart(atchoum, {
type: "line",
data: {
labels: {{ atchoumDate|raw }},
datasets: [{
label: "Nombre d'éternuements au support",
data: {{ atchoumNb|raw }},
borderColor: "blue",
tension: 0.3,
options: {
responsive: true,
scales: {
y: {
beginAtZero: true
}
},
animations: {
y: {
easing: 'easeInOutElastic',
from: (ctx) => {
if (ctx.type === 'data') {
if (ctx.mode === 'default' && !ctx.dropped) {
ctx.dropped = true;
return 0;
}
}
}
}
},
}
}]
}
})
You are defining your options in the dataset itself.
The options object is supposed to be on the same level as the type and data fields since the options are for the entire chart and not for a single dataset.
const options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 7, 9, 20, 8]
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.js"></script>
</body>

hide label on doughnut chart of chartjs

Thanks for the help in advance.I am using doughnut graph of chartjs.In it the percentage value labels are coming on the graph.Is there any way i can hide it.
var category_doughnut_datas = [80,5,5,10];
var category_doughnut__data = {
labels: ["Safe Zone", "Level 1","Level 2","Level 3"],
};
var category_doughnut_options = {
cutoutPercentage: 60,
legend: {
display: false,
position: "top",
paddingBottom: 16,
align: "start",
labels: {
fontColor: "#555555",
fontSize: 20,
boxWidth: 0,
},
},
tooltips: {
displayColors: false,
},
responsive: true,
};
var dough_ctx = document.getElementById("overallStatus").getContext("2d");
if (dough_ctx) {
var myDoughnutChart = new Chart(dough_ctx, {
type: "doughnut",
data: category_doughnut__data,
options: category_doughnut_options,
});
}
Since you dont specify any options to draw it on the chart in your options and its not default chart.js behaviour I expect you defined it as defaults somewhere, in which case you can in your options object in the plugins section specify datalabels: false to stop it from rendering:
Chart.register(ChartDataLabels);
Chart.defaults.plugins.datalabels.color = '#fff';
Chart.defaults.plugins.datalabels.formatter = (value, ctx) => {
let sum = 0;
let dataArr = ctx.chart.data.datasets[0].data;
dataArr.map(data => {
sum += data;
});
let percentage = (value * 100 / sum).toFixed(2) + "%";
return percentage;
};
const options = {
type: 'doughnut',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
}]
},
options: {
plugins: {
datalabels: false // Removing this line shows the datalabels again
}
}
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.0.0/chartjs-plugin-datalabels.js"></script>
</body>
options.plugins.datalabels: false should be mentioned.
Without it, the value is set to be true by default.

How do you set x and y axis and Title for a line chart using charts.js?

This is using charts.js. This code only makes the line graph but the title, x axis and y axis does not show. I want to add title, and the names for those 2 axis onto the graph. what is wrong and how do you fix it? I also want to make the y axis to start from 0 and up.
async function chartDisplay() {
await getData1();
await getData2();
const ctx = document.getElementById('chart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'line',
data: {
labels: xLabels,
datasets: [{
data: ratingDataI,
label: "data1",
borderColor: "#3E95CD",
fill: false
},
{
data: ratingDataA,
label: "data2",
borderColor: "#3E95CD",
fill: false
}
]
},
options: {
responsive: true,
title: {
display: true,
text: 'Chart.js Line Chart'
},
tooltips: {
mode: 'label',
},
hover: {
mode: 'nearest',
intersect: true
},
scales: {
x: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Dates'
}
}],
y: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Value'
}
}]
}
}
});
}
the x and y should not be arrays but objects, also the scaleLabel prop is called title now. For all the changes please read the migration guide (https://www.chartjs.org/docs/master/getting-started/v3-migration.html)
Example:
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'pink'
}]
},
options: {
scales: {
y: {
beginAtZero: true,
title: {
display: true,
text: 'yAxis'
}
},
x: {
title: {
display: true,
text: 'xAxis'
}
}
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.1/chart.js"></script>
</body>

Render labels only when the data is available for a particular label

I'm creating an stack bar chart using chart.js. I need to hide the labels which don't have data on the current chart. As an example I want to only show "Prediction Success" label as data related to other labels are not there for the current date range. How can we do that?
You can use the legend filter like this:
var options = {
type: 'bar',
data: {
labels: ["Red", "Yellow", "Blue", "Yellow", "Green", "Purple", "Orange", "Green"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 0, 5, 6],
borderWidth: 1,
backgroundColor: 'red'
},
{
label: '# of NonVotes',
data: [],
borderWidth: 1,
backgroundColor: 'blue'
}
]
},
options: {
plugins: {
legend: {
labels: {
filter: (legendItem, chartData) => (legendItem, chartData, chartData.datasets[legendItem.datasetIndex].data.length > 0)
}
}
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.1.0/chart.js" integrity="sha512-LlFvdZpYhQdASf4aZfSpmyHD6+waYVfJRwfJrBgki7/Uh+TXMLFYcKMRim65+o3lFsfk20vrK9sJDute7BUAUw==" crossorigin="anonymous"></script>
</body>

Categories

Resources