Chartjs average line over bars - javascript

I use https://www.chartjs.org/. In the example below I list values for every day for two weeks. For that I want a line of the average values for this period.
Is it possible with chartjs and if so how?
I've started but it follows the bar locations and it should create a new path with fewer points.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<canvas id="canvas"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js"></script>
<script>
var ctx = document.getElementById('canvas').getContext('2d');
var mixedChart = new Chart(ctx, {
type: 'bar',
data: {
datasets: [{
label: 'Bar Dataset',
data: [1, 2, 3, 1, 3, 4, 7, 2, 4, 3, 1, 6, 5, 2],
backgroundColor: "#FF9881",
order: 2
}, {
label: 'Line Dataset',
data: [1, 2],
type: 'line',
borderColor: "#FF312D",
fill: false,
borderWidth: 1,
order: 1
}],
labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
},
options: {
"scales": {
"yAxes": [{
"ticks": {
"beginAtZero": true
}
}]
}
}
});
</script>
</body>
</html>

I would calculate the average and spread it over the whole graph like this:
const getLineData = (initialData, lengthOfDataChunks) => {
const numOfChunks = Math.ceil(initialData.length / lengthOfDataChunks);
const dataChunks = [];
for (var i = 0; i < numOfChunks; i++) dataChunks[i] = [];
initialData.forEach((entry, index) => {
const chunkNumber = Math.floor(index / lengthOfDataChunks);
dataChunks[chunkNumber]
dataChunks[chunkNumber].push(entry);
});
const averagedChunks = dataChunks.map(chunkEntry => {
const chunkAverage = chunkEntry.reduce(sumArray) / lengthOfDataChunks;
return chunkEntry.map(chunkEntryValue => chunkAverage);
});
return averagedChunks.flat();
}
const ctx = document.getElementById('canvas').getContext('2d');
const barData = [1, 2, 3, 1, 3, 4, 7, 2, 4, 3, 1, 6, 5, 2];
const sumArray = (accumulator, currentValue) => accumulator + currentValue;
const averageBarValue = barData.reduce(sumArray) / barData.length;
const lineData = getLineData(barData, 7);
var mixedChart = new Chart(ctx, {
type: 'bar',
data: {
datasets: [{
label: 'Bar Dataset',
data: barData,
backgroundColor: "#FF9881",
order: 2
}, {
label: 'Line Dataset',
data: lineData,
type: 'line',
borderColor: "#FF312D",
fill: false,
borderWidth: 1,
order: 1
}],
labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
},
options: {
"scales": {
"yAxes": [{
"ticks": {
"beginAtZero": true
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js"></script>
<canvas id="canvas"></canvas>
I hope I got your question right. If not, please let me know!

If your requirements are to draw just a flat, average line, I would go for
their official annotation plugin [chartjs-plugin-annotation].
I will insert a really basic, self-consistent example here, adapted from their documentation.
index.html:
<html>
<head>
<script src="index.js"></script>
</head>
<body>
<canvas id="canvas"></canvas>
</body>
</html>
anyname.js [which you then need to browserify into the index.js source file]:
/* the following is just a shortcut to register all the needed elements, for any chart.
more info here:
https://www.chartjs.org/docs/3.3.0/getting-started/integration.html#bundlers-webpack-rollup-etc */
const Chart = require("chart.js/auto");
const annotationPlugin = require("chartjs-plugin-annotation");
function average(ctx) {
const values = ctx.chart.data.datasets[0].data;
return values.reduce((a, b) => a + b, 0) / values.length;
}
const data = {
labels: ["1", "2", "3", "4", "5", "6", "7"],
datasets: [
{
label: "Sample Series",
data: [40, 100, 54, 34, 13, 78, 41]
}
]
};
const annotation = {
type: 'line',
borderColor: 'black',
borderDash: [6, 6],
borderDashOffset: 0,
borderWidth: 3,
label: {
enabled: true,
content: (ctx) => "Average: " + average(ctx).toFixed(2),
position: 'end'
},
scaleID: 'y',
value: (ctx) => average(ctx)
};
const config = {
type: 'bar',
data,
options: {
plugins: {
title: {
display: true,
text: "Sample Chart",
font: {
size: 14
}
},
annotation: {
annotations: {
annotation
}
}
}
}
};
// the annotation plugin needs to be registered, too
Chart.register(annotationPlugin);
document.addEventListener('DOMContentLoaded', () => {
const myChart = new Chart(document.getElementById('canvas'), config);
}, false);
Node required libraries [which you need to install for browserify to work]:
chart.js -- v. 3.7.1
chartjs-plugin-annotation -- v. 1.3.1
References:
https://www.chartjs.org/chartjs-plugin-annotation/1.2.0/samples/line/average.html

Related

Charjs: How to hide other lines on hover?

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>

Chartjs adding data values on the right legend

considering the following example:
$(document).ready(function() {
var ctx = document.getElementById('mycanvas').getContext('2d');
var chart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ["CL", "ML", "Spl.L", "PD", "Other Permissions"],
datasets: [{
label: "My First dataset",
backgroundColor: ['#F0CB8C', '#EE97A1', '#A9D5D4', '#E8A3D7', '#CFA3FD'],
data: [7, 3, 3, 4, 8],
}]
},
options: {
legend: {
position: 'right'
}
}
});
})
example
is there a way to have the data on the right of the single label?
like here:
You can add custom labels as advised by #LeeLenalee's solution
and here is your workin code :
$(document).ready(function() {
var ctx = document.getElementById('mycanvas').getContext('2d');
var chart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ["CL", "ML", "Spl.L", "PD", "Other Permissions"],
datasets: [{
label: "My First dataset",
backgroundColor: ['#F0CB8C', '#EE97A1', '#A9D5D4', '#E8A3D7', '#CFA3FD'],
data: [7, 3, 3, 4, 8],
}]
},
options: {
legend: {
labels: {
generateLabels: (chart) => {
const datasets = chart.data.datasets;
return datasets[0].data.map((data, i) => ({
text: `${chart.data.labels[i]} ${data}`,
fillStyle: datasets[0].backgroundColor[i],
}))}
}
}
}
});
})
.chart-container {
width: 280px;
height: 280px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
<div class="chart-container">
<canvas id="mycanvas"></canvas>
</div>

How to add a second datalabel to ChartJs bar charts?

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>

How could I put a string for the points on the x-axis?

I am using ChartJS v.2, and I would like to label arrayX by a string that will appear when the mouse will be on hover displaying the coordinates.
ArrayX being points (numbers) I should label with something.
data = {
labels: arrayX,
datasets: [{
label: 'ArrayY',
data: arrayY,
fill: false,
borderColor: 'rgb(75, 192, 192)',
tension: 0.1
}]
};
You can use the title callback for this:
var options = {
type: 'line',
data: {
labels: ["10", "15", "30", "80", "5000", "999999"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderWidth: 1
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderWidth: 1
}
]
},
options: {
tooltips: {
callbacks: {
title: (a) => ('Test string: ' + a[0].label)
}
}
}
}
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/2.9.4/Chart.js"></script>
</body>
I solved using this way, more easy.
options: {
tooltips: {
callbacks: {
title:function(tooltipItems, data){
return 'Y: ' + tooltipItems[0].xLabel;
}
}
}
}

Different xAxis label, max and colors for drilldown in Highcharts

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!

Categories

Resources