Chart.JS Can not read property '_meta' of Undefined - javascript

I am attempting to build a basic bar chart, but I am getting the error in the title. I have used alert() to verify that the array I want to populate the chart with holds data, but something is still not fishing out properly with the syntax. Can someone examine and let me know what I need to do better in order to make the chart produce?
var ctx = document.getElementById('cvtree').getContext('2d');
var chart = new Chart(ctx, {
type: 'bar',
data: {
labels: yoylabels,
datasets: [{
label: 'Pay By Person',
backgroundColor: 'rgba(0, 129, 214, 0.8)',
data: numericdollarvals
}]
},
options: {
},
legend: {
display: false,
position: 'top',
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
callback: function (value, index, values) {
if (parseInt(value) >= 1000) {
return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
} else {
return '$' + value;
}
}
}
}]
}
});

You are unexpectedly closing off the options property, before setting all the options.
Here is the correct syntax :
var ctx = document.getElementById('cvtree').getContext('2d');
var chart = new Chart(ctx, {
type: 'bar',
data: {
labels: yoylabels,
datasets: [{
label: 'Pay By Person',
backgroundColor: 'rgba(0, 129, 214, 0.8)',
data: numericdollarvals
}]
},
options: {
legend: {
display: false,
position: 'top',
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
callback: function(value, index, values) {
if (parseInt(value) >= 1000) {
return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
} else {
return '$' + value;
}
}
}
}]
}
}
});

Related

How to add a toggle inside a title of the barchart js

I have this barchart created in the ChartJS last version.
I want to add a toggle button inside the barchart title, as shown in this picture: https://i.stack.imgur.com/1KMyB.png
This is my barchart code:
var ctx = document.getElementById("myBarChart");
var myBarChart = new Chart(ctx, {
type: 'bar',
data: {
labels: [],
datasets: [{
label: "Valor",
backgroundColor: "rgba(2,117,216,1)",
borderColor: "rgba(2,117,216,1)",
data: [],
}],
},
options: {
plugins: {
datalabels: {
anchor: 'end',
align: 'top',
formatter: function (value, context) {
if (value != 0) {
return new Date(value * 1000).toISOString().substr(11, 8);
} else {
value = " "
return value;
}
},
font: {
weight: 'bold'
}
}
},
responsive: true,
tooltips: {
/* intersect: false, */
callbacks: {
title: function (tooltipItem, data) {
return data['labels'][tooltipItem[0]['index']];
},
label: function (tooltipItem, data) {
return new Date(parseInt(data['datasets'][0]['data'][tooltipItem[
'index']]) * 1000).toISOString().substr(11,
8);
},
},
},
scales: {
xAxes: [{
time: {
unit: 'month'
},
gridLines: {
display: false
},
}],
yAxes: [{
ticks: {
min: 0,
suggestedMax: 36000,
stepSize: 3600,
beginAtZero: true,
},
}],
},
}
});
Is it something possible to do?
If someone know how to do this in the last version of the chartjs, please help me.                                                                  
                                               
You can make use of the core plugin API to write a custom plugin that does it. The better and easyer option to to not use the title of chart.js and put a div above your chart and put your title and the toggle in that div with HTML

ChartJS How to set color to just one bar

I have this barChart and I'm with difficult to set a color by script to just one bar of the index.
Bellow is my chartbar code:
var ctx = document.getElementById("myBarChart");
var myBarChart = new Chart(ctx, {
type: 'bar',
data: {
labels: [],
datasets: [{
label: "Valor",
backgroundColor: "rgba(2,117,216,1)",
borderColor: "rgba(2,117,216,1)",
data: [],
}],
},
options: {
plugins: {
datalabels: {
anchor: 'end',
align: 'top',
formatter: function (value, context) {
if (value != 0) {
return new Date(value * 1000).toISOString().substr(11, 8);
} else {
value = " "
return value;
}
},
font: {
weight: 'bold'
}
}
},
responsive: true,
tooltips: {
/* intersect: false, */
callbacks: {
title: function (tooltipItem, data) {
return data['labels'][tooltipItem[0]['index']];
},
label: function (tooltipItem, data) {
return new Date(parseInt(data['datasets'][0]['data'][tooltipItem[
'index']]) * 1000).toISOString().substr(11,
8);
},
},
},
scales: {
xAxes: [{
time: {
unit: 'month'
},
gridLines: {
display: false
},
}],
yAxes: [{
ticks: {
min: 0,
suggestedMax: 36000,
stepSize: 3600,
beginAtZero: true,
},
}],
},
}
});
I have tried this:
myBarChart.data.datasets[0].backgroundColor[0]
But it doesnt work.
If someone know how to do this in the last version of the chartjs, please help me.
You can provide an array to the backgroundColor property. In this array you can fill it with the default color except for the index where you want the bar to be a different collor

How to format the left legend on chartjs

I have a chart and I want to format the values on the left side to money format. The image is where I want to change.
the chart
That's my code so far:
this.Chart = new Chart('kpi', {
type: 'bar',
data: {
labels: cat,
datasets: [
{
data: Value,
label: "Categorias",
backgroundColor: 'rgba(26, 179, 148, 0.4)',
borderColor: 'rgba(26, 179, 148, 1)',
borderWidth: 2
}
]
},
options: {
events: ['mousemove', 'click'],
},
hover: {
mode: "nearest",
},
scales: {
yAxes: [{
id: 'data',
type: 'linear',
ticks: {
beginAtZero: true
}
}]
},
title: {
display: true,
text: 'Categorias',
fontSize: 20,
fontColor: 'rgba(26, 179, 148, 1)',
fontStyle: 'normal'
},
tooltips: {
mode: "nearest",
callbacks: {
title: (item, data) => {
},
label: (item, data) => {
let index = item.index;
item.value = numeral(data.datasets[0].data[index]).format('$0,0.00');
return `${data.labels[index]}: ${item.value}`
}
}
}
}
});
I want to format with ".format('$0,0.00')" like on the label, or something like that, but I don't know how to format those values.
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
scales: {
yAxes: [{
ticks: {
// Include a dollar sign in the ticks
callback: function(value, index, values) {
return '$' + value;
}
}
}]
}
}
});
This is a sample code to format the y axis value from the documentation page of chartjs. You can use this callback to format your labels.

Showing Percentage and Total In stacked Bar Chart of chart.js

I am working on stacked Bar charts using chart.js.
I need to show labels in middle of Bars as percentage and total sum on top of bars stacked together. Currently, I am able to show their percentage after searching for code. But that percentages are not correct mathematically. I have added that code in js fiddle. Hope I got some help for it. I am just weak in js.
https://jsfiddle.net/n4nish/hca3wdgq/4/
HTML -
var data = [{
label: 'New',
backgroundColor: '#1d3f74',
data: [6310, 5742, 4044, 5564]
}, {
label: 'Repeat',
backgroundColor: '#6c92c8',
data: [11542, 12400, 12510, 11450]
}];
var options = {
maintainAspectRatio: false,
spanGaps: false,
responsive: true,
legend: {
display: true,
position: 'bottom',
labels: {
fontColor: "#fff",
boxWidth: 14,
fontFamily: 'proximanova'
}
},
tooltips: {
mode: 'label',
callbacks: {
label: function (tooltipItem, data) {
var type = data.datasets[tooltipItem.datasetIndex].label;
var value = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
var total = 0;
for (var i = 0; i < data.datasets.length; i++)
total += data.datasets[i].data[tooltipItem.index];
if (tooltipItem.datasetIndex !== data.datasets.length - 1) {
return type + " : " + value.toFixed(0).replace(/(\d)(?=(\d{3})+\.)/g, '1,');
} else {
return [type + " : " + value.toFixed(0).replace(/(\d)(?=(\d{3})+\.)/g, '1,'), "Overall : " + total];
}
}
}
},
plugins: {
datalabels: {
formatter: function (value, ctx) {
let sum = 0;
let dataArr = ctx.chart.data.datasets[0].data;
dataArr.map(data => {
sum += data;
});
let percentage = (value * 100 / sum).toFixed(0) + "%";
return percentage;
},
font: {
weight: "normal"
},
color: "#fff"
}
},
scales: {
xAxes: [{
stacked: true,
gridLines: {
display: false
},
ticks: {
fontColor: "#fff"
}
}],
yAxes: [{
stacked: true,
display: false,
ticks: {
fontColor: "#fff"
}
}]
}
};
var ctx = document.getElementById("mychart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Jun", "July", "Aug", "Sept"],
datasets: data
},
options: options
});
You can set options that will apply to:
all labels in the chart:
options.plugins.datalabels.*
only a single dataset:
dataset.datalabels.*
// Label formatter function
const formatter = (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(0)}%`;
};
const data = [{
// stack: 'test',
label: "New",
backgroundColor: "#1d3f74",
data: [6310, 5742, 4044, 5564],
// Change options only for labels of THIS DATASET
datalabels: {
color: "white",
formatter: formatter
}
},
{
// stack: 'test',
label: "Repeat",
backgroundColor: "#6c92c8",
data: [11542, 12400, 12510, 11450],
// Change options only for labels of THIS DATASET
datalabels: {
color: "yellow",
formatter: formatter
}
}
];
const options = {
maintainAspectRatio: false,
spanGaps: false,
responsive: true,
legend: {
display: true,
position: "bottom",
labels: {
fontColor: "#fff",
boxWidth: 14,
fontFamily: "proximanova"
}
},
tooltips: {
mode: "label",
callbacks: {
label: function(tooltipItem, data) {
const type = data.datasets[tooltipItem.datasetIndex].label;
const value =
data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
let total = 0;
for (let i = 0; i < data.datasets.length; i++)
total += data.datasets[i].data[tooltipItem.index];
if (tooltipItem.datasetIndex !== data.datasets.length - 1) {
return (
type + " : " + value.toFixed(0).replace(/(\d)(?=(\d{3})+\.)/g, "1,")
);
} else {
return [
type +
" : " +
value.toFixed(0).replace(/(\d)(?=(\d{3})+\.)/g, "1,"),
"Overall : " + total
];
}
}
}
},
plugins: {
// Change options for ALL labels of THIS CHART
datalabels: {
color: "#white",
align: "center"
}
},
scales: {
xAxes: [{
stacked: true,
gridLines: {
display: false
},
ticks: {
fontColor: "#fff"
}
},
{
type: 'category',
offset: true,
position: 'top',
ticks: {
fontColor: "#fff",
callback: function(value, index, values) {
return data[0].data[index] + data[1].data[index]
}
}
}
],
yAxes: [{
stacked: true,
display: false,
ticks: {
fontColor: "#fff"
}
}]
}
};
const ctx = document.getElementById("mychart").getContext("2d");
new Chart(ctx, {
type: "bar",
data: {
labels: ["Jun", "July", "Aug", "Sept"],
datasets: data
},
options: options
});
body {
background: #20262e;
font-family: Helvetica;
padding-top: 50px;
}
#mychart {
height: 300px;
}
<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.2/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#0.4.0/dist/chartjs-plugin-datalabels.min.js"></script>
<canvas id="mychart"></canvas>
Codepen

How to use same data / labels on two y axes in Chart.js

I have one set of data I'm using in angular-chart.js, but I want both y-axis to use the same data set (for the labels, I don't wish to chart the same data twice). If I just duplicate the code for both y axes, the left axes shows the correct data, while the right axes shows a scale from -1 at the minimum to 1 max.
...
scales: {
yAxes: [{
id: 'y-axis-1',
type: 'linear',
display: true,
position: 'left',
ticks: {
beginAtZero: false,
callback: function(value, index, values) {
if (parseInt(value) >= 1000) {
return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
} else {
return '$' + value;
}
}
}
},
{
id: 'y-axis-2',
type: 'linear',
display: true,
position: 'right',
ticks: {
beginAtZero: false,
callback: function(value, index, values) {
if (parseInt(value) >= 1000) {
return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
} else {
return '$' + value;
}
}
}
}
], ...
How to make the same labels show up on both y axes?
You can use the following chart plugin to show/use the same labels/ticks on two different y-axis :
Chart.plugins.register({
beforeInit: function(chart) {
chart.options.scales.yAxes[1].ticks.suggestedMin = Math.min.apply(this, chart.data.datasets[0].data);
chart.options.scales.yAxes[1].ticks.suggestedMax = Math.max.apply(this, chart.data.datasets[0].data);
}
});
- add this at the beginning of your script
ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ
Chart.plugins.register({
beforeInit: function(chart) {
chart.options.scales.yAxes[1].ticks.suggestedMin = Math.min.apply(this, chart.data.datasets[0].data);
chart.options.scales.yAxes[1].ticks.suggestedMax = Math.max.apply(this, chart.data.datasets[0].data);
}
});
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
datasets: [{
label: 'LINE',
data: [3, 1, 4, 2, 5],
backgroundColor: 'rgba(0, 119, 290, 0.2)',
borderColor: 'rgba(0, 119, 290, 0.6)',
fill: false
}]
},
options: {
scales: {
yAxes: [{
id: 'y-axis-0',
position: 'left',
ticks: {
stepSize: 1
}
}, {
id: 'y-axis-1',
position: 'right',
ticks: {
stepSize: 1
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="ctx"></canvas>

Categories

Resources