I wanted to construct a bar chart using chart.js. I typed this code:
<!DOCTYPE html>
<html>
<head>
<title>Bar chart</title>
<script src="Chart.js"></script>
</head>
<body>
<canvas id="canvas" width="256" height="256"></canvas>
<script>
var my = new Chart(chr).Bar(data);
var chr = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var data = {
dataset: [
{
label: "my first dataset",
fillColor: "blue",
strokeColor: "green",
data: [65, 53, 80, 83, 55, 45]
}
]
};
var myfirstChart = new Chart(chr).Bar(data);
</script>
console.log(ctx);
</body>
</html>
...and it says there is cannot "read property length undefined".
What is the error and how to correct it?
Try this code:
Html:
<canvas id="canvas" width="256" height="256"></canvas>
Js:
var chr = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var data = {
type: "bar",
data: {
labels: ["One", "Two"],
datasets: [{
label: "my first dataset",
backgroundColor: ["#F7464A", "#46BFBD", "#FDB45C"],
fillColor: "blue",
strokeColor: "green",
data: [65, 53]
}]
}
};
var myfirstChart = new Chart(ctx, data);
Joseph i have made some correction in script as following. its working fine try this.
<script>
var chr = document.getElementById("canvas");
var ctx = chr.getContext("2d");
ctx.canvas.width = 800;
var data = {
type: "bar",
data: {
labels: ["One", "Two"],
datasets: [{
label: "my first dataset",
backgroundColor: ["#F7464A", "#46BFBD", "#FDB45C"],
fillColor: "blue",
strokeColor: "green",
data: [65, 53]
}]
}
};
var myfirstChart = new Chart(chr , data);
</script>
Related
// Set Chart Global Variables
let x_values = [0];
let y_values = [0];
let new_number = 0;
let index = 0;
// Intialize The Chart Canvas
let ctx = document.getElementById('chart_canvas').getContext('2d');
// Create New Line Chart
my_chart = new Chart(ctx, {
type: "line",
data: {
labels: [x_values[0]],
datasets: [{
backgroundColor: [],
fill: true,
pointStyle: "circle",
label: "Values",
data: [y_values[0]]
}]
}
});
// ------ Local Functions ------
function add() {
index = x_values.length;
new_number += 10;
my_chart.data.labels.push(index);
x_values.push(index);
my_chart.data.datasets.forEach((dataset) => {
dataset.data.push(new_number);
//The line below might be wrong since it is not changing the background color.
dataset.backgroundColor.push("#88c0d080");
});
my_chart.update();
}
function subtract() {
index = x_values.length;
new_number -= 10;
my_chart.data.labels.push(index);
x_values.push(index);
my_chart.data.datasets.forEach((dataset) => {
dataset.data.push(new_number);
//This line below might be wrong since it is not changing the background color.
dataset.backgroundColor.push("#bf616a80");
});
my_chart.update();
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Testing Chart.js Line Chart</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js" integrity="sha512-sW/w8s4RWTdFFSduOTGtk4isV1+190E/GghVffMA9XczdJ2MDzSzLEubKAs5h0wzgSJOQTRYyaz73L3d6RtJSg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>
<body>
<button type="button" onclick="add()" id="btnAdd">Add 10</button>
<button type="button" onclick="subtract()" id="btnSubtract">Subtract 10</button>
<canvas id="chart_canvas">Your browser does not support the HTML5 canvas tag.</canvas>
</body>
</html>
Expected Behavior:
When the "Add 10" button is clicked, a new point entry needs to be added with a backgroundColor fill
color of teal (#88c0d080).
When the "subtract 10" button is clicked, a new point entry needs to be added with a backgroundColor fill color of red (#bf616a80).
Current Behavior:
Only the point background color is being changed rather than the backgroundColor fill color.
Your help will be much appreciated.
You can use segment styling that update dynamicly when you add new data:
const options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'orange',
fill: true,
segment: {
backgroundColor: (ctx) => (ctx.p0.parsed.y > ctx.p1.parsed.y ? 'red' : 'teal')
}
}]
},
options: {}
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
const c = new Chart(ctx, options);
document.getElementById('add').addEventListener('click', () => {
c.data.labels.push(c.data.labels.length);
c.data.datasets[0].data.push(c.data.datasets[0].data[c.data.datasets[0].data.length - 1] + 10)
c.update()
});
document.getElementById('subb').addEventListener('click', () => {
c.data.labels.push(c.data.labels.length);
c.data.datasets[0].data.push(c.data.datasets[0].data[c.data.datasets[0].data.length - 1] - 10)
c.update()
});
<body>
<button id="add">
Add 10
</button>
<button id="subb">
Subtract 10
</button>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.js"></script>
</body>
Consider the following code.
var chartData = {
labels: ["January", "February", "March", "April", "May", "June"],
datasets: [{
fillColor: "#79D1CF",
strokeColor: "#79D1CF",
data: [60, 80, 81, 56, 55, 40]
}]
};
var ctx = document.getElementById("myChart1").getContext("2d");
var myLine = new Chart(ctx, {
type: "line",
data: chartData,
showTooltips: false,
onAnimationComplete: function() {
var ctx = this.chart.ctx;
ctx.font = this.scale.font;
ctx.fillStyle = this.scale.textColor
ctx.textAlign = "center";
ctx.textBaseline = "bottom";
this.datasets.forEach(function(dataset) {
dataset.points.forEach(function(points) {
ctx.fillText(points.value, points.x, points.y - 10);
});
})
}
});
<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/3.6.2/chart.min.js"></script>
<canvas id="myChart1" height="300" width="500"></canvas>
Because I use the function in the onAnimationComplete in different graphs, I like to create a JavaScript file where I collect all the functions and use them. For example
var chart = new Chart(ctx, eval(config));
chart.options.animation.onComplete = function () {
window["AnimationComplete1"](chart);
}
function AnimationComplete1(chart) {
var ctx = chart.ctx;
ctx.textAlign = "center";
ctx.textBaseline = "bottom";
chart.data.datasets.forEach(function (dataset) {
dataset.points.forEach(function (points) {
ctx.fillText(points.value, points.x, points.y - 10);
});
})
}
In this code, the problem is that in the function I don't have access to the point from the dataset from chart.data.datasets. Also, I don't have access to the scale for font and textColor.
Is there a way to access those values from a common function?
The Chart.js animation onComplete callback function must be defined inside the chart options.
options: {
animation: {
onComplete: ctx => {
// do your stuff
}
}
}
Please take a look at your amended code below and see how it works.
var chartData = {
labels: ["January", "February", "March", "April", "May", "June"],
datasets: [{
fillColor: "#79D1CF",
strokeColor: "#79D1CF",
data: [60, 80, 81, 56, 55, 40]
}]
};
new Chart('myChart1', {
type: "line",
data: chartData,
options: {
animation: {
onComplete: ctx => {
console.log(ctx.chart.data.datasets);
console.log(ctx.chart.options.scales.x);
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js"></script>
<canvas id="myChart1" height="300" width="500"></canvas>
I'm trying to recreate this example:
chart.js bar chart color change based on value
With the following code
<script src="/chart.js/dist/Chart.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
window.myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 3, 3],
fillColor: "rgba(220,220,220,0.5)",
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
borderWidth: 1
}]
},
});
var bars = myChart.datasets[0].bars;
for (i = 0; i < bars.length; i++) {
var color = "green";
//You can check for bars[i].value and put your conditions here
if (bars[i].value < 3) {
color = "red";
} else if (bars[i].value < 5) {
color = "orange"
} else if (bars[i].value < 8) {
color = "yellow"
} else {
color = "green"
}
bars[i].fillColor = color;
}
myChart.update();
</script>
but I get in console the TypeError:
myChart.datasets is undefined on the line var bars = myChart.datasets[0].bars;
Do you have an idea what I'm overlooking?
Thank you
Here is the complete example you want.
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>
<script>
//Creating a barchart with default values
var myChart = new Chart(document.getElementById("myChart"), {
"type": "bar",
"data": {
"labels": ["January", "February", "March", "April", "May", "June", "July"],
"datasets": [{
"label": "My First Dataset",
"data": [65, 59, 80, 81, 56, 55, 40],
"fill": false,
"backgroundColor": ["#fb4d4d", "#fb9d4d", "#f8fb4d", "#98fb4d", "#4effee", "#4cb9f8", "#574cf8"],
"borderColor": ["#fb4d4d", "#fb9d4d", "#f8fb4d", "#98fb4d", "#4effee", "#4cb9f8", "#574cf8"],
"borderWidth": 1
}]
},
"options": {
"scales": {
"yAxes": [{
"ticks": {
"beginAtZero": true
}
}]
}
}
});
//Getting the bar-chart existing values
var bars = myChart.config.data.datasets[0];
var data = bars.data;
//Updating the existing value (object which holds value)
for (i = 0; i < data.length; i++) {
var bgcolor = "";
var brcolor = "";
if (data[i] < 30) {
bgcolor = "red";
brcolor = "red";
} else if (data[i] < 50) {
bgcolor = "orange";
brcolor = "orange";
} else if (data[i] < 80) {
bgcolor = "yellow";
brcolor = "yellow";
} else {
bgcolor = "green";
brcolor = "green";
}
bars.backgroundColor[i] = bgcolor;
bars.borderColor[i] = brcolor;
}
//Triggering the chart update in 3 seconds.
setTimeout(function(){
myChart.update();
}, 3000);
</script>
your dataset was empty, was not being done as the example quoted
The correct way to do as the example you mentioned is:
var barChartData = {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [
{
label: '# of Votes',
data: [12, 19, 3, 5, 3, 3],
fillColor: "rgba(220,220,220,0.5)",
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
borderWidth: 1
}
]
};
var ctx = document.getElementById('myChart').getContext('2d');
window.myObjBar = new Chart(ctx).Bar(barChartData, {
responsive : true
});
var bars = myObjBar.datasets[0].bars;
for(i=0;i<bars.length;i++){
var color="green";
//You can check for bars[i].value and put your conditions here
if(bars[i].value<3){
color="red";
}
else if(bars[i].value<5){
color="orange"
}
else if(bars[i].value<8){
color="yellow"
}
else{
color="green"
}
bars[i].fillColor = color;
}
myObjBar.update(); //update the cahrt
Here is an example working :)
the jsfiddle below shows the problem.
The first data inserts are fine, but when the length of the data set is capped at 10 you see the undesired behaviour where data points are animated top-down instead of moving left. It's extremely distracting.
http://jsfiddle.net/kLg5ntou/32/
setInterval(function () {
data.labels.push(Math.floor(Date.now() / 1000));
data.datasets[0].data.push(Math.floor(10 + Math.random() * 80));
// limit to 10
data.labels = data.labels.splice(-10);
data.datasets[0].data = data.datasets[0].data.splice(-10);
chart.update(); // addData/removeData replaced with update in v2
}, 1000);
Is there a way to have the line chart move left having the newly inserted data point appear on the right? As opposed to the wavy distracting animation?
thanks
This code uses streaming plugin and works as expected.
http://jsfiddle.net/nagix/kvu0r6j2/
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-streaming#1.5.0/dist/chartjs-plugin-streaming.min.js"></script>
var ctx = document.getElementById("chart").getContext("2d");
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: [],
datasets: [{
label: "My First dataset",
backgroundColor: "rgba(95,186,88,0.7)",
borderColor: "rgba(95,186,88,1)",
pointBackgroundColor: "rgba(0,0,0,0)",
pointBorderColor: "rgba(0,0,0,0)",
pointHoverBackgroundColor: "rgba(95,186,88,1)",
pointHoverBorderColor: "rgba(95,186,88,1)",
data: []
}]
},
options: {
scales: {
xAxes: [{
type: 'realtime'
}]
},
plugins: {
streaming: {
onRefresh: function(chart) {
chart.data.labels.push(Date.now());
chart.data.datasets[0].data.push(
Math.floor(10 + Math.random() * 80)
);
},
delay: 2000
}
}
}
});
You should use 2.5.0 chartsjs
here it works :
http://jsfiddle.net/kLg5ntou/93
var data = {
labels: ["0", "1", "2", "3", "4", "5", "6"],
datasets: [
{
label: "My First dataset",
fillColor: "rgba(95,186,88,0.7)",
strokeColor: "rgba(95,186,88,1)",
pointColor: "rgba(0,0,0,0)",
pointStrokeColor: "rgba(0,0,0,0)",
pointHighlightFill: "rgba(95,186,88,1)",
pointHighlightStroke: "rgba(95,186,88,1)",
data: [65, 59, 80, 81, 56, 55, 40]
}
]
};
var ctx = document.getElementById("chart").getContext("2d");
var chart = new Chart(ctx, {type: 'line', data: data});
setInterval(function () {
chart.config.data.labels.push(Math.floor(Date.now() / 1000));
chart.config.data.datasets[0].data.push(Math.floor(10 + Math.random() * 80));
// limit to 10
chart.config.data.labels.shift();
chart.config.data.datasets[0].data.shift();
I have some trouble;
I want to change code
in row labels (this is parameters of chart.js)
but my labels change and i want to set this parameter
Example
From this
var nData = {
labels: [1,2,3,4,5,6,7,8]
}
to
var nData = {
labels: [**"1,2,3,4,5,6,7,8,9"**]
}
From
var nData = {
labels: [1,2,3,4,5,6,7,8],
datasets: [
{
fillColor: "rgba(220,220,220,0)",
strokeColor: "rgba(220,220,220,1)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,0,220,1)",
data: [array[0].amount, array[1].amount, array[2].amount, array[3].amount, array[4].amount, array[5].amount, array[6].amount,array[7].amount],
title : "My revenue"
}
]
};
var opts = {
scaleLineColor: "gray",
}
var ctx = document.getElementById("canvas").getContext("2d");
window = new Chart(ctx).Line(nData,opts);
}
like this,
but this variant is not work.
var a="1,2,3,4,5,6,7,8";
var nData = {
labels: [eval(a)],
datasets: [
{
fillColor: "rgba(220,220,220,0)",
strokeColor: "rgba(220,220,220,1)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,0,220,1)",
data: [array[0].amount, array[1].amount, array[2].amount, array[3].amount, array[4].amount, array[5].amount, array[6].amount,array[7].amount],
title : "My revenue"
}
]
};
var opts = {
scaleLineColor: "gray",
}
var ctx = document.getElementById("canvas").getContext("2d");
window = new Chart(ctx).Line(nData,opts);
}
If I understand you correctly it's just:
nData.labels = [nData.labels.join()];
It's equivalent to
nData.labels = [nData.labels.join(',')];
because the default value for join is a comma.
A third option is to do
nData.labels = [nData.labels.toString()];
Which in this case also will return the desired result.