I am using Chart.js v3, below is the code but it is not hiding. The goal is that when I hover over a line, it hides other lines and their labels. The code is given below:
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/moment#^2"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.1/chart.min.js"></script>
</head>
<body>
<canvas id="myChart" width="300" height="200"></canvas>
<script>
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx, {
type: "line",
data: {
labels: [1, 2, 3, 4, 5],
datasets: [{
label: "Line 1",
data: [1, 2, 3, 4, 5],
borderColor: "red",
backgroundColor: "rgba(255,0,0,0.2)"
}, {
label: "Line 2",
data: [5, 4, 3, 2, 1],
borderColor: "blue",
backgroundColor: "rgba(0,0,255,0.2)"
}, {
label: "Line 3",
data: [2, 4, 6, 8, 10],
borderColor: "green",
backgroundColor: "rgba(0,255,0,0.2)"
}]
},
options: {
hover: {
mode: "index",
intersect: true
},
animation: {
duration: 0
}
}
});
</script>
</body>
</html>
I think you should implement onHover hook in the chart options. Based on hovered element you can hide the others.
2 points of attention I guess:
hover mode should 'point' and not 'index' otherwise all datasets will be hidden
to have a consistent view on chart, you should set min and max on y scale.
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx, {
type: "line",
data: {
labels: [1, 2, 3, 4, 5],
datasets: [{
label: "Line 1",
data: [1, 2, 3, 4, 5],
borderColor: "red",
backgroundColor: "rgba(255,0,0,0.2)"
}, {
label: "Line 2",
data: [5, 4, 3, 2, 1],
borderColor: "blue",
backgroundColor: "rgba(0,0,255,0.2)"
}, {
label: "Line 3",
data: [2, 4, 6, 8, 10],
borderColor: "green",
backgroundColor: "rgba(0,255,0,0.2)"
}]
},
options: {
scales: {
y: {
beginAtZero: true,
max: 10
}
},
onHover(e, elements, chart) {
if (elements.length) {
for (const el of elements) {
const dsCount = chart.data.datasets.length;
for (let i = 0; i < dsCount; i++) {
if (i !== el.datasetIndex) {
chart.setDatasetVisibility(i, false);
}
}
}
chart.update();
} else {
const dsCount = chart.data.datasets.length;
for (let i = 0; i < dsCount; i++) {
chart.setDatasetVisibility(i, true);
}
chart.update();
}
},
hover: {
mode: "point",
intersect: true
},
animation: {
duration: 0
}
}
});
.myChartDiv {
max-width: 600px;
max-height: 400px;
}
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/moment#^2"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.1/chart.min.js"></script>
</head>
<body>
<div class="myChartDiv">
<canvas id="myChart" width="600" height="400"/>
</div>
</body>
</html>
I have a chart as below, it has a datalabel inside each stacked bar showing a percentage. Now I am wanting to add a second set of datalabel on top of each bar(consider each set of stacked bar as one bar) that shows the month, say for person 1, the right bar says current month(may), the middle one says last month(april), the left bar says march.
I only need three month.
Any help is appreciated.
const trend_options = {
responsive: true,
maintainAspectRatio: false,
plugins: {
datalabels: {
formatter: function(value, ctx) {
const otherDatasetIndex = ctx.datasetIndex === 0 ? 1 : 0;
const total = ctx.chart.data.datasets[otherDatasetIndex].data[ctx.dataIndex] + value;
return `${(value / total * 100).toFixed()}%`;
},
font: {
weight: "bold"
},
color: "#fff",
display: function(context) {
let index = context.dataIndex;
let value = context.dataset.data[index];
return value > 0; // display labels with a value greater than 0
}
},
},
scales: {
x: {
stacked: true
},
y: {
stacked: true,
suggestedMax: 15,
ticks: {
beginAtZero: true,
stepSize: 5,
}
}
},
};
const app_data_trend = [{
label: 'App Month 1 TW',
data: [3, 4, 5, 6, 4, 4, 4],
backgroundColor: '#007bff',
stack: 'Stack 0',
},
{
label: 'App Month 1 jira',
data: [3, 4, 5, 4, 3, 2, 3],
backgroundColor: '#6DB526',
stack: 'Stack 0',
},
{
label: 'App Month 2 TW',
data: [4, 4, 4, 3, 2, 5, 4],
backgroundColor: 'pink',
stack: 'Stack 1',
},
{
label: 'App Month 2 jira',
data: [4, 2, 5, 2, 3, 3, 4],
backgroundColor: 'red',
stack: 'Stack 1',
},
{
label: 'App Month 3 TW',
data: [2, 4, 5, 2, 4, 5, 3],
backgroundColor: 'grey',
stack: 'Stack 2',
},
{
label: 'App Month 3 jira',
data: [1, 1, 2, 4, 4, 3, 5],
backgroundColor: 'yellow',
stack: 'Stack 2',
},
]
const ctx8 = document.getElementById("tsa-applications-trending");
const chart8 = new Chart(ctx8, {
plugins: [ChartDataLabels],
type: 'bar',
data: {
labels: ['person1', 'person2', 'person3', 'person4'],
datasets: app_data_trend
},
options: trend_options,
});
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.7.1/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.0.0/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#2.0.0"></script>
<div class="chart-container" style="position: relative; height:80vh; width:80vw">
<canvas id="tsa-applications-trending"></canvas>
</div>
I have a setup where I am generating multiple Highcharts with different sets of data. I now started implementing a drilldown, which needs different labels for xAxis, max needs to be changed and I would like to set the colors for each bar.
regarding the xAxis, the object I am using get the data for the drilldown seems alright to me, but instead of using the name, the i of the loop is being displayed
(5) […]
0: {…}
data: Array(5) [ 3, 8, 3, … ]
id: "dd1"
name: "Bad!"
type: "column"
for the max value, which should be 5 for the basic chart but unset for the drilldown, I tried
drilldown: {
yAxis: {
max: 100
}
}
but it did not do anything.
TBH I did not try myself at colors yet, expected outcome would be that the bars are being colored according to the quality of the week, e.g. Bad week = red up to Fantastic = green
I also tried setting the chart type for the drilldown in general (right now I am setting 'type': 'column' for every data object, which appears redundant to me, but I could not figure out whether I can use something like ...drilldown.chart: { 'type':'column'} to define a general setting for the drilldown, but this too does not show any results.
I have tried implementing several setup examples using either functions bound to charts.events.drilldown or plotoptions.series.points.events.click but my very limited knowledge of Highcharts and JavaScript prevented me from succeeding.
Code:
// Fallback for browsers that cannot handle Object.values (i.e. that do not support ES6)
if (!Object.values) {
Object.values = function(source) {
var result = Object.keys(source).map(function(x) {
return source[x];
});
return result;
};
}
// Setting general HighCharts options
var options = {
chart: {
type: 'areaspline'
},
credits: {
enabled: false
},
legend: {
enabled: false
},
xAxis: {
type: 'category'
},
yAxis: {
title: {
enabled: false
},
max: 5
},
series: [{
fillColor: {
linearGradient: {
x1: 0,
y1: 0,
x2: 0,
y2: 1
},
stops: [
[0, '#F0A830'],
[1, '#f4f4f4']
]
},
marker: {
fillColor: 'white',
lineWidth: 2,
lineColor: '#F0A830',
radius: 5
},
lineColor: '#F0A830',
lineWidth: 5,
}],
plotOptions: {
series: {
marker: {
enabled: false,
symbol: 'circle'
}
}
},
drilldown: {
yAxis: {
max: 100
},
chart: {
'type': 'column'
},
drillUpButton: {
theme: {
fill: 'white',
'stroke-width': 1,
stroke: 'silver',
r: 0,
states: {
hover: {
fill: '#a4edba'
},
select: {
stroke: '#039',
fill: '#a4edba'
}
}
}
}
}
};
// Temporary data delivery
var circlesData = {
"0": {
"title": "MyTeam",
"values": [4, 3, 2, 3, 4],
"weeks": [1, 2, 3, 4, 5],
"weeksTotal": [6, 7, 8, 9, 10],
"valuesDetail": {
"valuesDetailLabel": ["Bad!", "Hmm", "Itwasokay", "Prettygood", "Fantastic"],
"valuesDetailData": {
0: [3, 4, 4, 1, 15],
1: [2, 12, 5, 3, 1],
2: [18, 2, 2, 2, 2],
3: [3, 2, 4, 1, 5],
4: [1, 2, 1, 1, 15]
}
}
},
"1": {
"title": "YourTeam",
"values": [1, 4, 5, 2, 3],
"weeks": [1, 2, 3, 4, 5],
"weeksTotal": [6, 7, 8, 9, 10],
"valuesDetail": {
"valuesDetailLabel": ["Bad!", "Hmm", "Itwasokay", "Prettygood", "Fantastic"],
"valuesDetailData": {
0: [3, 8, 3, 1, 4],
1: [3, 12, 4, 3, 1],
2: [4, 2, 2, 2, 2],
3: [3, 2, 4, 5, 8],
4: [1, 2, 1, 1, 15]
}
}
}
}
console.log(circlesData);
var circlesDataString = JSON.stringify(circlesData); //this just turns the object array 'info' into a string
var obj = JSON.parse(circlesDataString);
console.log('Loading initiated...');
// Loop for creating individual HighCharts
Object.keys(obj).forEach(function(item) {
// Create container div
$('#outerContainer').append('<div class="innerContainer" id="circles' + item + '"></div>');
// Get data of last iteration and determin quality of last week for color coding/wording
var latestScore = circlesData[item].values.slice(-1)[0];
console.log('latestScore: ' + latestScore)
var chartColor = '';
var weekText = '';
var className = '';
if (latestScore < 2.5) {
chartColor = '#FD6E72';
chartColorLight = '#fc8385';
weekText = 'Bad week';
} else if (latestScore >= 2.5 && latestScore < 3.5) {
chartColor = '#FFCC73';
chartColorLight = '#FBD486';
weekText = 'Ok week';
} else {
chartColor = '#2CCC76';
chartColorLight = '#82DB9D';
weekText = 'Good week';
}
// create array for first chart view
var chartData = [];
var len = circlesData[item].values.length;
for (i = 0; i < len; i++) {
chartData.push({
'name': 'w' + circlesData[item].weeks[i],
'y': circlesData[item].values[i],
'drilldown': 'dd' + circlesData[item].values[i]
});
};
// set array for drilldown items
var drillDown = [];
for (i = 0; i < len; i++) {
drillDown.push({
'type': 'column',
'id': 'dd' + circlesData[item].values[i],
'data': circlesData[item].valuesDetail.valuesDetailData[i],
'name': circlesData[item].valuesDetail.valuesDetailLabel[i]
});
};
console.log('This is drillDown');
console.log(drillDown);
// Setting individual Highcharts options per Circle
options.series[0] = {
name: circlesData[item].title,
data: chartData,
color: chartColor,
fillColor: {
linearGradient: {
x1: 0,
y1: 0,
x2: 0,
y2: 1
},
stops: [
[0, chartColor],
[1, '#f4f4f4']
]
},
};
// Set drilldown options
options.drilldown.series = drillDown;
options.title = {
text: circlesData[item].title
};
options.subtitle = {
text: weekText,
style: {
color: chartColor,
}
};
console.log(options);
// Call Highcharts
$('#circles' + item).highcharts(options);
console.log('Circle' + item + ' loaded...');
});
https://codepen.io/anon/pen/eqRPGV
xAxis labels: For labels to have different names, each data point should have a name, like: 0: [["Bad!",3], ["Hmm",8], ["Itwasokay",3], ["Prettygood",1], ["Fantastic",4]]
Max value: drilldown.yAxis is not an API and therefore it won't work. Instead, the global max value should be updated. In this case, we can set it to null conditionally, as: if(options.drilldown) options.yAxis.max = null;
For each column to have different color, you need to overwrite the global colors array, options.colors with the desired one and define property: 'colorByPoint': true for each series object under drilldown object.
For chart type, drilldown.chart: { 'type':'column'} won't work, because there is no chart API for drilldown. Though it appears redundant, but each drilldown.series object will have its own chart type. In this case 'column'.
Also, the id in each drilldown.series object should be unique. In your code instead of doing this way, 'id': 'dd' + circlesData[item].values[i], you can do it using weeks array like: 'id': 'dd' + circlesData[item].weeks[i]. Because circlesData["0"].values have duplicate data.
Below is the updated code. You can refer jsfiddle.
// Fallback for browsers that cannot handle Object.values (i.e. that do not support ES6)
if (!Object.values) {
Object.values = function(source) {
var result = Object.keys(source).map(function(x) {
return source[x];
});
return result;
};
}
// Setting general HighCharts options
var options = {
chart: {
type: 'areaspline'
},
colors: ['#ED561B', '#DDDF00', '#24CBE5', '#058DC7', '#50B432'],
credits: {
enabled: false
},
legend: {
enabled: false
},
xAxis: {
type: 'category'
},
yAxis: {
title: {
enabled: false
},
max: 5
},
series: [{
fillColor: {
linearGradient: {
x1: 0,
y1: 0,
x2: 0,
y2: 1
},
stops: [
[0, '#F0A830'],
[1, '#f4f4f4']
]
},
marker: {
fillColor: 'white',
lineWidth: 2,
lineColor: '#F0A830',
radius: 5
},
lineColor: '#F0A830',
lineWidth: 5,
}],
plotOptions: {
series: {
marker: {
enabled: false,
symbol: 'circle'
}
}
},
drilldown: {
drillUpButton: {
theme: {
fill: 'white',
'stroke-width': 1,
stroke: 'silver',
r: 0,
states: {
hover: {
fill: '#a4edba'
},
select: {
stroke: '#039',
fill: '#a4edba'
}
}
}
}
}
};
// Temporary data delivery
var circlesData = {
"0": {
"title": "MyTeam",
"values": [4, 3, 2, 3, 4],
"weeks": [1, 2, 3, 4, 5],
"weeksTotal": [6, 7, 8, 9, 10],
"valuesDetail": {
"valuesDetailLabel": ["Bad!", "Hmm", "Itwasokay", "Prettygood", "Fantastic"],
"valuesDetailData": {
0: [["Bad!",3], ["Hmm",4], ["Itwasokay",4], ["Prettygood",1], ["Fantastic",15]],
1: [["Bad!",2], ["Hmm",12], ["Itwasokay",5], ["Prettygood",3], ["Fantastic",1]],
2: [["Bad!",18], ["Hmm",2], ["Itwasokay",2], ["Prettygood",2], ["Fantastic",2]],
3: [["Bad!",3], ["Hmm",2], ["Itwasokay",4], ["Prettygood",1], ["Fantastic",5]],
4: [["Bad!",1], ["Hmm",2], ["Itwasokay",1], ["Prettygood",1], ["Fantastic",15]]
}
}
},
"1": {
"title": "YourTeam",
"values": [1, 4, 5, 2, 3],
"weeks": [1, 2, 3, 4, 5],
"weeksTotal": [6, 7, 8, 9, 10],
"valuesDetail": {
"valuesDetailLabel": ["Bad!", "Hmm", "Itwasokay", "Prettygood", "Fantastic"],
"valuesDetailData": {
0: [["Bad!",3], ["Hmm",8], ["Itwasokay",3], ["Prettygood",1], ["Fantastic",4]],
1: [["Bad!",3], ["Hmm",12], ["Itwasokay",4], ["Prettygood",3], ["Fantastic",1]],
2: [["Bad!",4], ["Hmm",2], ["Itwasokay",2], ["Prettygood",2], ["Fantastic",2]],
3: [["Bad!",3], ["Hmm",2], ["Itwasokay",4], ["Prettygood",5], ["Fantastic",8]],
4: [["Bad!",1], ["Hmm",2], ["Itwasokay",1], ["Prettygood",1], ["Fantastic",15]]
}
}
}
}
console.log(circlesData);
var circlesDataString = JSON.stringify(circlesData); //this just turns the object array 'info' into a string
var obj = JSON.parse(circlesDataString);
console.log('Loading initiated...');
// Loop for creating individual HighCharts
Object.keys(obj).forEach(function(item) {
// Create container div
$('#outerContainer').append('<div class="innerContainer" id="circles' + item + '"></div>');
// Get data of last iteration and determin quality of last week for color coding/wording
var latestScore = circlesData[item].values.slice(-1)[0];
console.log('latestScore: ' + latestScore)
var chartColor = '';
var weekText = '';
var className = '';
if (latestScore < 2.5) {
chartColor = '#FD6E72';
chartColorLight = '#fc8385';
weekText = 'Bad week';
} else if (latestScore >= 2.5 && latestScore < 3.5) {
chartColor = '#FFCC73';
chartColorLight = '#FBD486';
weekText = 'Ok week';
} else {
chartColor = '#2CCC76';
chartColorLight = '#82DB9D';
weekText = 'Good week';
}
// create array for first chart view
var chartData = [];
var len = circlesData[item].values.length;
for (i = 0; i < len; i++) {
chartData.push({
'name': 'w' + circlesData[item].weeks[i],
'y': circlesData[item].values[i],
'drilldown': 'dd' + circlesData[item].weeks[i]
});
};
// set array for drilldown items
var drillDown = [];
for (i = 0; i < len; i++) {
drillDown.push({
'type': 'column',
'id': 'dd' + circlesData[item].weeks[i],
'data': circlesData[item].valuesDetail.valuesDetailData[i],
'name':'w' + circlesData[item].weeks[i],
'colorByPoint': true,
});
};
console.log('This is drillDown');
console.log(drillDown);
// Setting individual Highcharts options per Circle
options.series[0] = {
name: circlesData[item].title,
data: chartData,
color: chartColor,
fillColor: {
linearGradient: {
x1: 0,
y1: 0,
x2: 0,
y2: 1
},
stops: [
[0, chartColor],
[1, '#f4f4f4']
]
},
};
// Set drilldown options
options.drilldown.series = drillDown;
options.title = {
text: circlesData[item].title
};
options.subtitle = {
text: weekText,
style: {
color: chartColor,
}
};
//do this conditionally
if(options.drilldown) options.yAxis.max = null;
console.log('option', options);
// Call Highcharts
$('#circles' + item).highcharts(options);
console.log('Circle' + item + ' loaded...');
});
Hope this helps!