How do I display a different chartjs tooltip title? - javascript

I am displaying a mixed bar and line chart using chartjs. I have successfully managed to display different content in the tooltip when your hover over the line chart, or the bars, but using the same condition does not work to display a different title:
callbacks: {
title: function(tooltipItem, data) {
if (tooltipItem.datasetIndex === 0){
return data['datasets'][0]['label'];
}else{
return data['datasets'][1]['label'];
}
}
}
I am using PHP values to populate data into the main chart. Here is the code for the main chart:
var ctx_<?=$chartname?> = document.getElementById('<?=$chartname?>').getContext('2d');
new Chart(ctx_<?=$chartname?>, {
type: 'bar',
data: {
labels: [<?=$labels?>], //label array needs to go here
datasets: [{
label: 'Overall Average Score',
notes: ['','','','',''],
data: [<?=$averages?>],
pointBackgroundColor: '#6600CC',
pointRadius: 6,
pointBorderColor: 'rgb(255, 255, 255)',
pointHoverRadius:8,
pointHoverBorderWidth: 2,
pointHoverBorderColor: 'rgb(255, 255, 255)',
fill: false,
// Changes this dataset to become a line
type: 'line'
},{
label: '<?=$forename?>\'s Score',
notes: [<?=$notes?>],
data: [<?=$scores?>] //data array needs to go in here
}],
},
options: groupBarChartOptions
});
However, instead of populating the tooltip title as 'Overall Average Score' it populates the line graph tooltip title of 'Pupil Name's Score'
I am using the same
if (tooltipItem.datasetIndex === 0){
condition in the following label callback, and it works.

This should work for what you want:
title: (tooltipItem, data) => {
return data['datasets'][tooltipItem[0].datasetIndex]['label']
}
working example: https://jsfiddle.net/Leelenaleee/bcwky40z/4/

Related

Is there a way to change the react-chart-js tooltip only on a graph?

I have the following:
const labels = historicosData.map(historico => {
const localDate = new Date(historico.fechaIngreso);
return localDate.toLocaleString('es-ES', { month: 'long' })
});
//const labels = historicosData.map(({ anio }) => anio);
// const labels = [123, 321, 456, 123, 4568]
const data = {
labels,
datasets: [
{
label: 'Valores históricos',
fill: false,
backgroundColor: 'rgba(75,192,192,0.4)',
borderColor: 'rgba(75,192,192,1)',
pointBorderColor: 'rgba(75,192,192,1)',
pointBackgroundColor: '#fff',
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: 'rgba(75,192,192,1)',
pointHoverBorderColor: 'rgba(220,220,220,1)',
pointHoverBorderWidth: 10,
pointRadius: 10,
pointHitRadius: 10,
data: historicosData.map(({ valor }) => valor),
},
],
};
And it displays the following graph:
Is there a way where I can change the default message of the tooltip (the one saying 'mayo') for a personalized message?
My main purpose is to make the X bottom axis to display only the months' name and display the whole date when the user's hover over one specific point
You can use the options prop as follows to customize the tooltip title:
const options = {
responsive: true,
plugins:
{
tooltip:
{
callbacks:
{
title: (context) =>
{
return context[0].label
},
}
},
},
}
Then pass options as a prop to your Line component:
<Line options = {options} data = {data} />
In the example above, I'm returning context[0].label which is the label you already see on the x-axis. You can change the return value to anything you want, and you can put other necessary logic within the callback as well.
For example, you may choose to return context[0].parsed.x rather than the label. Or you may choose to use this value to put together the final title to return.
Read more about tooltip configuration in the docs.

ChartJS doughnut colors not showing from a Flask app. All gray

Looking for some help here. The doughnut chart is rendering properly, but all the colors are gray. I've scoured the chartjs site and googled, but I can't seem to solve this.
Here's my code:
#app.route('/doughnut_chart')
def doughnut_chart():
values = []
labels =['good', 'mediocre','bad']
colors = ['rgba(0, 153, 0, 0.1)', 'rgba(0,153,153,0.1)','rgba(102,153,51,0.1)']
good_high = db.session.query(func.sum(Jf_Q1.highwellbeing)/func.sum(Jf_Q1.good_job)).\
filter(Jf_Q1.working==1).filter(Jf_Q1.good_job==1)
good_mod = db.session.query(func.sum(Jf_Q1.moderatewellbeing)/func.sum(Jf_Q1.good_job)).\
filter(Jf_Q1.working==1).filter(Jf_Q1.good_job==1)
good_low = db.session.query(func.sum(Jf_Q1.lowwellbeing)/func.sum(Jf_Q1.good_job)).\
filter(Jf_Q1.working==1).filter(Jf_Q1.good_job==1)
values = [0.82483097725875845114*100,0.14935464044253226798*100,0.01966810079901659496*100]
return render_template('results.html', values=values,labels=labels, colors=colors)
and my script code on the web page:
new Chart(document.getElementById("doughnut-chart"), {
type: 'doughnut',
data: {
labels : {{labels | safe}},
backgroundColor: {{colors | safe}},
datasets:
[{ data : {{values | safe}}
}]
},
options: {
title: {
display: true,
text: 'Doughnut Chart Title'
}
}
});
Here's how it looks in Chrome's inspector:
new Chart(document.getElementById("doughnut-chart"), {
type: 'doughnut',
data: {
labels : ['good', 'mediocre', 'bad'],
backgroundColor: ['rgba(0, 153, 0, 0.1)', 'rgba(0,153,153,0.1)', 'rgba(102,153,51,0.1)'],
datasets:
[{ data : [82.48309772587584, 14.935464044253226, 1.9668100799016592]
}]
},
options: {
title: {
display: true,
text: 'Doughnut Chart Title'
}
}
});
I've tried hex colors such as:
backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9"]
But still no dice
This is what is looks like in Chrome and in FF:
my chart
Any assistance is greatly appreciated.
Thanks
Fixed it!. datasets is a list of objects. I needed to place the backgroundColor option inside datasets as such:
datasets:
[{ data : [82.48309772587584, 14.935464044253226, 1.9668100799016592],
backgroundColor: ['rgba(0, 153, 0, 0.1)', 'rgba(0,153,153,0.1)', 'rgba(102,153,51,0.1)'],
fill: true
}],
I had it outside. RTFM! lol

Multiple line labels for chart js

I have this radar chart in chart.js which has 5 labels. The labels are quite long so I want to show them in two lines in HTML but when I use "\n" it doesn't make a new line!
These are my labels:
labels: ["COMMUNICATION \n SKILL ", "PRODUCT AND PROCESS \n KNOWLEDGE "]
As you can see I'm trying to have "communication skill" and "product and process knowledge" both in two lines but it shows them in one line!
What's the correct way to do it?
UPDATE
The labels is in script tag:
var myChart = new Chart(ctx, {
type: 'radar',
data: {
labels: ["COMMUNICATION SKILL ", "PRODUCT AND PROCESS KNOWLEDGE "],
datasets: [{
label: labs,
data: dps,
backgroundColor: [
'rgba(255, 99, 132, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
],
borderWidth: 1
},
options: {
maintainAspectRatio: true,
scale: {
ticks:{
beginAtZero: true,
max: 4
}
}
}
});
I believe what you are looking for is answered here:
ChartJS New Lines '\n' in X axis Labels or Displaying More Information Around Chart or Tooltip with ChartJS V2
The solution is to pass a nested array as an input to 'labels' - with each element in the nested array representing a new line of text in your label. So in your case the following should work:
labels: [["COMMUNICATION","SKILL"], ["PRODUCT AND PROCESS","KNOWLEDGE"]]
Just read the docs https://www.chartjs.org/docs/latest/charts/radar.html
you need your dataset to have the property data and that should be an array. The values in the array will correspond with the values in the labels by their index number.
data: {
labels: ['Running', 'Swimming', 'Eating', 'Cycling'],
datasets: [{
data: [20, 10, 4, 2]
}]
}

Is it possible to add individual labels to Chart.JS bars?

I have a fully functional Chart.JS Barchart which loads as intended, however I would like to add the username to each bar which is associated to them so administrators (who can see all entries) can distinguish between them.
function BarChart(data) {
var barChartData = {
labels: data.Month,
datasets: [
{
label: 'Weight (kg)',
fillColor: "rgba(220,220,220,0.5)",
backgroundColor: "rgba(46, 44, 211, 0.7)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
data: data.Weight
},
{
label: 'Steps',
fillColor: "rgba(0,0,0,0.5)",
backgroundColor: "rgba(215, 44, 44, 0.7)",
highlightFill: "rgba(0,0,0,0.5)",
highlightStroke: "rgba(0,0,0,0.5)",
data: data.Steps
}
]
}
var ctx = document.getElementById("barchart").getContext("2d");
window.myBar =new Chart(ctx, {
type: 'bar',
data: barChartData,
options: { responsive: true }
});
I have successfully passed through the Usernames and they can be called by using data.User, however when I append this to the Steps or Weight label, I end up with "Steps for: admin,admin,admin" (since I have three entries, all from admin).
Is it possible to have it so each bar has the username it belongs to?
Maybe not quite what you asked for, but you could add it to the tooltip.
options: {
tooltips:{
callbacks: {
afterLabel: function(e){return "added By:" +data.User[e.datasetIndex][e.index]}
}
}
}
https://jsfiddle.net/r71no58a/7/

How to add a dataset toggle to Chart.js?

I'm using Chart.js to create a line chart. I would like to have four different datasets that will all be visibile by default, but can be toggled on and off by clicking a button. How can this be achieved? I can't seem to find an answer in the documentation. .addData(), .removeData() and .update() all seem to be used for adding or removing values to existing datasets, but not adding or removing entire datasets. I would think this would be fairly commonly used feature but I can't find an answer anywhere.
After thoroughly researching this, there doesn't appear to be any built in function to toggle entire datasets. I used the .destroy() function to remove the entire existing chart, and then some logic to redraw it with the necessary datasets.
EDIT: Here's a fiddle with my full code if it's helpful to anyone -> http://jsfiddle.net/21xg27kr/4/
Here is a line chart with two datasets. By updating the datasets and calling the .update() method. The benefit here is you don't need to destroy the whole chart, and there is a nice animated transition which can be disabled.
TL:DR; solution on jsfiddle
Step by Step:
Bring in Chart.js from a CDN
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
Create the HTML Canvas element that will hold the chart
<canvas id="line-chart"></canvas>
Hide/Show buttons for this example
Creating the chart, and the functions to update it live - notice that the same integer data needs to be copied in two places - in the initial creation, and in the show function.
<script>
lineChart = new Chart(document.getElementById("line-chart"), {
type: 'line',
data: {
labels: ['A', 'B', 'C', 'D'],
datasets: [
{
label: "Set 1",
fill: true,
backgroundColor: "rgba(90,181,242,0.2)",
borderColor: "rgba(179,181,198,1)",
pointBorderColor: "#fff",
pointBackgroundColor: "rgba(179,181,198,1)",
data: [3, 1, 1, 0]
}, {
label: "Set 2",
fill: true,
backgroundColor: "rgba(255,99,132,0.2)",
borderColor: "rgba(255,99,132,1)",
pointBorderColor: "#fff",
pointBackgroundColor: "rgba(255,99,132,1)",
pointBorderColor: "#fff",
data: [1, 3, 3, 5]
}
]
},
options: {
title: {
display: true,
text: 'Chart Title'
}
}
});
function restoreLayer2(){
lineChart.data.datasets[1].data = [1, 3, 3, 5];
lineChart.update();
}
function removeLayer2() {
lineChart.data.datasets[1].data = [];
lineChart.update();
}
</script>

Categories