.datasets is undefined when trying to access bars from chart.js - javascript

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 :)

Related

How to access all data in a function with ChartJs?

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>

chart.js Is there way to color line chart ticks depending on value

I have simple chart.js line chart:
I need to color lines between ticks, depending on previous value like that:
If next value is lower than prev line must be red, if higher color is green.
Any ideas how to achieve this?
You can check the following solution.
var ctx = document.getElementById('myChart').getContext('2d');
//adding custom chart type
Chart.defaults.multicolorLine = Chart.defaults.line;
Chart.controllers.multicolorLine = Chart.controllers.line.extend({
draw: function(ease) {
var
startIndex = 0,
meta = this.getMeta(),
points = meta.data || [],
colors = this.getDataset().colors,
area = this.chart.chartArea,
originalDatasets = meta.dataset._children
.filter(function(data) {
return !isNaN(data._view.y);
});
function _setColor(newColor, meta) {
meta.dataset._view.borderColor = newColor;
}
if (!colors) {
Chart.controllers.line.prototype.draw.call(this, ease);
return;
}
for (var i = 2; i <= colors.length; i++) {
if (colors[i-1] !== colors[i]) {
_setColor(colors[i-1], meta);
meta.dataset._children = originalDatasets.slice(startIndex, i);
meta.dataset.draw();
startIndex = i - 1;
}
}
meta.dataset._children = originalDatasets.slice(startIndex);
meta.dataset.draw();
meta.dataset._children = originalDatasets;
points.forEach(function(point) {
point.draw(area);
});
}
});
// build colors sequence
const data = [0, 10, 5, 2, 20, 30, 45];
const availableColors = ['red', 'green'];
let colors = [];
data.forEach(item => {
availableColors.forEach(color => {
colors.push(color)
})
})
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'multicolorLine',
// The data for our dataset
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
borderColor: 'rgb(255, 99, 132)',
data: data,
//first color is not important
colors: ['', ...colors]
}]
},
// Configuration options go here
options: {}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.min.js"></script>
<canvas id="myChart"></canvas>

Construct a bar chart using chart.js

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>

chart js tooltip how to control the data that show

I'm using chart.js plugin and using a group chart by bar view.
when i hover a group of bars i can see a tooltip that show me the data of this bars.
but i what to change the tooltip to show my only single data when I'll hover the bar data.
and I what to show diffrent data info.
jsfiddle example
var ctx = document.getElementById("errorChart").getContext("2d");
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
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)",
data: [65, 0, 0, 0, 0, 0, 0]
},
{
label: "My Second dataset",
fillColor: "rgba(151,187,205,0.5)",
strokeColor: "rgba(151,187,205,0.8)",
highlightFill: "rgba(151,187,205,0.75)",
highlightStroke: "rgba(151,187,205,1)",
data: [28, 48, 40, 19, 86, 27, 90]
}
]
};
var myBarChart = new Chart(ctx).Bar(data);
You could extend the bar graph to include this functionality. By default it will return both bars at the index you have hovered over, it will also check for multiple bars at the area you hovered before creating the tooltip and put any extras in that were missing.
So to do this you will need to override two functions getBarsAtEvent and showToolTip here is an example and fiddle
I have tried to make it clear the two important areas that have changed look at the comments in the extended bar type. Small changes were also made to any reference of the helpers as before they were within the scope but now they need to explicitly call Chart.helpers
Chart.types.Bar.extend({
name: "BarOneTip",
initialize: function(data){
Chart.types.Bar.prototype.initialize.apply(this, arguments);
},
getBarsAtEvent : function(e){
var barsArray = [],
eventPosition = Chart.helpers.getRelativePosition(e),
datasetIterator = function(dataset){
barsArray.push(dataset.bars[barIndex]);
},
barIndex;
for (var datasetIndex = 0; datasetIndex < this.datasets.length; datasetIndex++) {
for (barIndex = 0; barIndex < this.datasets[datasetIndex].bars.length; barIndex++) {
if (this.datasets[datasetIndex].bars[barIndex].inRange(eventPosition.x,eventPosition.y)){
//change here to only return the intrested bar not the group
barsArray.push(this.datasets[datasetIndex].bars[barIndex]);
return barsArray;
}
}
}
return barsArray;
},
showTooltip : function(ChartElements, forceRedraw){
console.log(ChartElements);
// Only redraw the chart if we've actually changed what we're hovering on.
if (typeof this.activeElements === 'undefined') this.activeElements = [];
var isChanged = (function(Elements){
var changed = false;
if (Elements.length !== this.activeElements.length){
changed = true;
return changed;
}
Chart.helpers.each(Elements, function(element, index){
if (element !== this.activeElements[index]){
changed = true;
}
}, this);
return changed;
}).call(this, ChartElements);
if (!isChanged && !forceRedraw){
return;
}
else{
this.activeElements = ChartElements;
}
this.draw();
console.log(this)
if (ChartElements.length > 0){
//removed the check for multiple bars at the index now just want one
Chart.helpers.each(ChartElements, function(Element) {
var tooltipPosition = Element.tooltipPosition();
new Chart.Tooltip({
x: Math.round(tooltipPosition.x),
y: Math.round(tooltipPosition.y),
xPadding: this.options.tooltipXPadding,
yPadding: this.options.tooltipYPadding,
fillColor: this.options.tooltipFillColor,
textColor: this.options.tooltipFontColor,
fontFamily: this.options.tooltipFontFamily,
fontStyle: this.options.tooltipFontStyle,
fontSize: this.options.tooltipFontSize,
caretHeight: this.options.tooltipCaretSize,
cornerRadius: this.options.tooltipCornerRadius,
text: Chart.helpers.template(this.options.tooltipTemplate, Element),
chart: this.chart
}).draw();
}, this);
}
return this;
}
});
then to use it just do what you did before but use BarOneTip (call it whatever you like, what ever is in the name attribute of the extended chart will be available to you.
var ctx = document.getElementById("errorChart").getContext("2d");
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
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)",
data: [65, 0, 0, 0, 0, 0, 0]
},
{
label: "My Second dataset",
fillColor: "rgba(151,187,205,0.5)",
strokeColor: "rgba(151,187,205,0.8)",
highlightFill: "rgba(151,187,205,0.75)",
highlightStroke: "rgba(151,187,205,1)",
data: [28, 48, 40, 19, 86, 27, 90]
}
]
};
var myBarChart = new Chart(ctx).BarOneTip(data);
I should mention that if chartjs gets updated you would need to manually put any changes to the functions into the overridden ones

How in javascript string convert in code?

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.

Categories