I have a website displaying inplay stats from football matches, I have a large number of stats and want to try and get away from just line after line of numbers in a table. Im using jquery datatables and have added a drop down for each row of data with more stats. In this drop down I would like a canvas.js radar graph
The problem is I cant find a way round having to initialise each chart with lots of code and that code would then be repeated on every line of the table, as a busy time that could be over 100 matches
below is the code of what I want to achieve but I want that in every row of a datatable, ideally I would like to initialise the graphs once and just have a single line of code in my datatable with the numbers
Any ideas ?
<!doctype html>
<html>
<head>
<title>Radar Chart</title>
<script src="dist/2.8.0/Chart.min.js"></script>
<script src="utils.js"></script>
<style>
canvas {
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
</style>
</head>
<body>
<button id="save-btn">Save Chart Image</button>
<div style="width:40%">
<canvas id="canvas"></canvas>
</div>
<script>
var randomScalingFactor = function() {
return Math.round(Math.random() * 100);
};
var color = Chart.helpers.color;
var config = {
type: 'radar',
data: {
labels: [['Shots on', ' Target'], ['Shots Off', 'Target'], 'Corners', 'possession (out of 10)'],
datasets: [{
label: 'Home team',
backgroundColor: color(window.chartColors.red).alpha(0.2).rgbString(),
borderColor: window.chartColors.red,
pointBackgroundColor: window.chartColors.red,
data: [
'5',
'7',
'4',
'6',
'2'
]
}, {
label: 'Away Team',
backgroundColor: color(window.chartColors.blue).alpha(0.2).rgbString(),
borderColor: window.chartColors.blue,
pointBackgroundColor: window.chartColors.blue,
data: [
'2',
'1',
'3',
'5',
'0'
]
}]
},
options: {
legend: {
position: 'top',
},
title: {
display: true,
text: 'In Play Stats'
},
scale: {
ticks: {
beginAtZero: true
}
}
}
};
window.onload = function() {
window.myRadar = new Chart(document.getElementById('canvas'), config);
};
</script>
</body>
</html>
One way I could think of is creating a function, if all of your charts are similar and only few parameters change, for example in the following example I've considered chartId, labels, dataset and title to be varying. You can also aim to write function that creates datasets given certain parameters:
var randomScalingFactor = function() {
return Math.round(Math.random() * 100);
};
window.chartColors = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(75, 192, 192)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(201, 203, 207)'
};
var color = Chart.helpers.color;
var labels = [
['Shots on', ' Target'],
['Shots Off', 'Target'], 'Corners', 'possession (out of 10)'
];
var datasets = [{
label: 'Home team',
backgroundColor: color(window.chartColors.red).alpha(0.2).rgbString(),
borderColor: window.chartColors.red,
pointBackgroundColor: window.chartColors.red,
data: ['5', '7', '4', '6', '2']
}, {
label: 'Away Team',
backgroundColor: color(window.chartColors.blue).alpha(0.2).rgbString(),
borderColor: window.chartColors.blue,
pointBackgroundColor: window.chartColors.blue,
data: ['2', '1', '3', '5', '0']
}];
window.onload = function() {
window.myRadar = createChart('canvas', labels, datasets, 'In Play Stats');
};
function createChart(chartId, labels, dataset, title) {
return new Chart(document.getElementById(chartId), {
type: 'radar',
data: {
labels: labels,
datasets: dataset
},
options: {
legend: {
position: 'top',
},
title: {
display: true,
text: title
},
scale: {
ticks: {
beginAtZero: true
}
}
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<div style="width:40%; min-width: 700px;">
<canvas id="canvas" style="width: 700px;"></canvas>
</div>
Related
I am trying to add the datalabels onto my stacked bar/line chart in chartJS specifically at the line chart area. Because the values are not aligned with the Y-Axis, therefore I wanted to use chartJS datalabels plugin to show the values on top of the line chart only for better clarification when it is printed out.
What I tried:
#1 putting into config
const config = {
type: 'line',
data: data,
options: {
plugins: {
datalabels: {
anchor: 'end',
align: 'top',
formatter: function(value, context) {
return GetValueFormatted(value);
},
borderRadius: 4,
color: 'white',
font: {
weight: 'bold'
},
formatter: Math.round,
padding: 6
},
title: {
display: true,
text: 'Menu Performance Chart'
},
},
scales: {
y: {
stacked: true
}
}
},
};
#2 putting into specific dataset
const data = {
labels: labels,
datasets: [{
label: 'Sub Total Sales (RM)',
data: [
'111',
'22',
'31',
'12',
'71',
'110',
'22',
],
borderColor: 'rgb(255, 99, 132)',
backgroundColor: 'rgba(255, 99, 132, 0.2)',
stack: 'combined',
type: 'bar'
},
{
label: 'Total Amount Sold',
data: [
'11',
'2',
'3',
'1',
'7',
'10',
'2',
],
borderColor: 'rgb(255, 159, 64)',
backgroundColor: 'rgba(255, 159, 64, 0.2)',
stack: 'combined',
datalabels: {
color: '#FFCE56'
}
},
]
};
I even tried the two at the same time to see if there were any results. Could anyone assist me with this? Thank you in advance.
Here is my code demo in JSFiddle:
https://jsfiddle.net/4gat7rzs/4/
The plugin is not registered. See doc: https://chartjs-plugin-datalabels.netlify.app/guide/getting-started.html#registration
You should add the datalabels plugin instance to the chart config:
const config = {
type: 'line',
data: data,
plugins: [ChartDataLabels], // <- MUST BE ADDED
options: {
....
Basically, I want to change grid color of my chart.js chart.
Here is my code:
const options = {
scales: {
x: {
grid: {
color: 'rgba(255,0,0,0.1)',
borderColor: 'red'
}
},
y: {
grid: {
color: 'rgba(0,255,0,0.1)',
borderColor: 'green'
}
}
}
};
var chart0 = new Chart(document.getElementById("chart0"), {
type: 'bar',
data: {
labels: [some,lables,here],
datasets: [
{
data: dataarr0,
fill: true,
backgroundColor: 'rgb(255, 99, 132)'
}
],
options: options
}
});
Chart just didn't seem to care and stays the same color. What I am doing wrong?
The options have to be defined on the same level as the type and data are defined. Then it works fine:
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'
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderColor: 'orange'
}
]
},
options: {
scales: {
x: {
grid: {
color: 'red',
borderColor: 'green'
}
},
y: {
grid: {
color: 'red',
borderColor: 'green'
}
}
}
}
}
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>
I have a chartjs line chart that has multiple lines like that;
I have been trying to add a date-time selector but I am not able to update my chart because I don't get how to reach the datas of my chart. Here is my chart decleration;
var ctx = document.getElementById('canvas');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: time1, time2,
datasets: [
{
label: 'Temperature - 1',
data: temp1,
backgroundColor: 'transparent',
borderColor: 'red',
borderWidth: 3
},
{
label: 'Temperature - 2',
data: temp2,
backgroundColor: 'transparent',
borderColor: 'purple',
borderWidth: 3
},
{
label: 'Humidity - 1',
data: hum1,
backgroundColor: 'transparent',
borderColor: 'green',
borderWidth: 3
},
{
label: 'Humidity - 2',
data: hum2,
backgroundColor: 'transparent',
borderColor: 'yellow',
borderWidth: 3
}]
},
options: {
elements: {
line: {
tension: 0
}
},
scales: {
y: {
title: "Temperature/Humidity",
beginAtZero: true,
min: 10,
max: 60
}
}
}
});
time1, time2, temp1, temp2, hum1, hum2 are all array. When I want to update the chart using chart.update() function that I read at its own documentation, as I said I don't get it how to reach to data arrays like temp1, temp2.
Something like myChart.data.datasets.data would not work, making them like json;
{first_data:{
label: 'Temperature - 1',
data: temp1,
backgroundColor: 'transparent',
borderColor: 'red',
borderWidth: 3
}},
Doesn't work also, how can I reach to temp1 for example?
SOLUTION:
Because of my carelessness I had asked a nonsense question. Because of myChart.data.datasets is an object, I am able to reach to temp1 like myChart.data.datasets[0].data, sorry everyone
You will need to target the specific dataset you want to get the data from so to get the data of the Temperature - 1 dataset you will need to target it like this: myChart.data.datasets[0].data
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: 'orange'
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderColor: 'pink'
}
]
},
options: {}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
const myChart = new Chart(ctx, options);
console.log(myChart.data.datasets[0].label)
console.log(myChart.data.datasets[0].data)
<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>
I trying to use Chart.js in my web, but the chart won't appear and there's no error code in chrome console. I'm using Chart.js v2.7.2.
I tried any solution but doesn't help me, i also copy the code from chart.js documentation. what's wrong?
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue"],
datasets: [{
label: '# of Votes',
data: [12, 19],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>
Try this:
<html>
<head>
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
theme: "light1", // "light2", "dark1", "dark2"
animationEnabled: false, // change to true
title:{
text: "Basic Column Chart"
},
data: [
{
// Change type to "bar", "area", "spline", "pie",etc.
type: "column",
dataPoints: [
{ label: "apple", y: 10 },
{ label: "orange", y: 15 },
{ label: "banana", y: 25 },
{ label: "mango", y: 30 },
{ label: "grape", y: 28 }
]
}
]
});
chart.render();
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"> </script>
</body>
</html>
I'm a bit stuck on adding conditional background colours to a row in ChartJS, based on numbers on the vertical axis.
Eg.
If the vertical axis is between 0 - 6, background colour for those rows is green.
If the vertical axis is between 6 - 12 background colour for those rows is grey
If the vertical axis is > 12 background colour for those rows is red
Has anyone done something like this before?
I've attached a picture that roughly describes the functionality.
Cheers!
There is no option to do this with chartjs. However you can write your own plugin and draw the background by yourself in the beforeDraw hook for example.
var chart = new Chart(ctx, {
plugins: [{
beforeDraw: function(chart) {
//..
}
}]
});
You can get all the information to calculate the height of an y-axis-segment from the chart parameter.
I've included a snippet below how this could be implemented. Note however that this is more a proof of concept than a proper implementation:
var canvas = document.getElementById('myChart');
window.chartColors = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(51, 204, 51)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(201, 203, 207)'
};
var myLineChart = new Chart(canvas,
{
type: 'line',
data: {
labels: ['1', '2', '3', '4', '5'],
datasets: [
{
label: '# of Votes',
fill: false,
backgroundColor: window.chartColors.blue,
borderColor: window.chartColors.blue,
data: [2, 5, 12.5, 9, 6.3]
}
]
},
options: {
responsive: true,
title: {
display: true,
text: 'Conditional Background'
},
backgroundRules: [{
backgroundColor: window.chartColors.green,
yAxisSegement: 6
}, {
backgroundColor: window.chartColors.grey,
yAxisSegement: 12
}, {
backgroundColor: window.chartColors.red,
yAxisSegement: Infinity
}],
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
stepSize: 1
}
}]
}
},
plugins: [{
beforeDraw: function (chart) {
var ctx = chart.chart.ctx;
var ruleIndex = 0;
var rules = chart.chart.options.backgroundRules;
var yaxis = chart.chart.scales["y-axis-0"];
var xaxis = chart.chart.scales["x-axis-0"];
var partPercentage = 1 / (yaxis.ticksAsNumbers.length - 1);
for (var i = yaxis.ticksAsNumbers.length - 1; i > 0; i--) {
if (yaxis.ticksAsNumbers[i] < rules[ruleIndex].yAxisSegement) {
ctx.fillStyle = rules[ruleIndex].backgroundColor;
ctx.fillRect(xaxis.left, yaxis.top + ((i - 1) * (yaxis.height * partPercentage)), xaxis.width, yaxis.height * partPercentage);
} else {
ruleIndex++;
i++;
}
}
}
}]
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
<canvas id="myChart" width="400" height="250"></canvas>
Shiffty's answer is right on point, however it only works if the background values are present on the yAxis, which is not always the case... depends on what fits. A more generic solution is to calculate the actual values:
var canvas = document.getElementById('myChart');
window.chartColors = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(51, 204, 51)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(201, 203, 207)'
};
var myLineChart = new Chart(canvas,
{
type: 'line',
data: {
labels: ['1', '2', '3', '4', '5'],
datasets: [
{
label: '# of Votes',
fill: false,
backgroundColor: window.chartColors.blue,
borderColor: window.chartColors.blue,
data: [2, 5, 12.5, 9, 6.3]
}
]
},
options: {
responsive: true,
title: {
display: true,
text: 'Conditional Background'
},
backgroundRules: [{
backgroundColor: window.chartColors.green,
yAxisSegement: 6
}, {
backgroundColor: window.chartColors.grey,
yAxisSegement: 12
}, {
backgroundColor: window.chartColors.red,
yAxisSegement: 999999
}],
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
stepSize: 1
}
}]
}
},
plugins: [{
beforeDraw: function (chart) {
var rules = chart.chart.options.backgroundRules;
var ctx = chart.chart.ctx;
var yAxis = chart.chart.scales["y-axis-0"];
var xaxis = chart.chart.scales["x-axis-0"];
for (var i = 0; i < rules.length; ++i) {
var yAxisSegement = (rules[i].yAxisSegement > yAxis.ticksAsNumbers[0] ? yAxis.ticksAsNumbers[0] : rules[i].yAxisSegement);
var yAxisPosStart = yAxis.height - ((yAxisSegement * yAxis.height) / yAxis.ticksAsNumbers[0]) + chart.chart.controller.chartArea.top;
var yAxisPosEnd = (i === 0 ? yAxis.height : yAxis.height - ((rules[i - 1].yAxisSegement * yAxis.height) / yAxis.ticksAsNumbers[0]));
ctx.fillStyle = rules[i].backgroundColor;
ctx.fillRect(xaxis.left, yAxisPosStart, xaxis.width, yAxisPosEnd - yAxisPosStart + chart.chart.controller.chartArea.top);
}
}
}]
});