how to pass an array to bar chart.js - javascript

I have drawn charts using morris.js which is pretty easy, but I want to switch to charts.js library. I have an array which has 'date' and two other values, I want to plot the date values on x-axis and the rest two on y-axis using chart.js bar function.
In morris it was easy to define values separately for both the axis but I don't understand how to do this in chart.js.
function testChart(myArray){
new Chart(document.getElementById("churn-bar-chart"), {
type: 'bar',
myArray: {
labels: 'date',
datasets: [
{
backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
data: ['new', 'lost']
}
]
},
options: {
legend: { display: true },
title: {
display: true,
text: 'Predicted world population (millions) in 2050'
}
}
});
}
// myArray
var UserArray = new Array();
UserArray= [];
var obj2 = {};
obj2.date = Date;
obj2.new = newUser;
obj2.lost = lostUser;
UserArray.push(obj2);

Related

Chart JS how to display an array of data objects as bar chart

I want to display a bar chart - each bar is a user/student. And for each student, there will be an xAxis label displaying the students name
The below code is a VueJS computed property and called chartData
My data array for the bar chart is an array of objects. Here is how i generate it
let dataRow = this.responses.map((d) => {
return {
label: d.user.name,
data: [d.grade],
}
});
Here is how I generate my labels
let users = [];
this.responses.map((d) => {
users.push(d.user.name)
});
I then return on object with an array of labels and datasets with data being an array of objects
return {
labels: users,
datasets: [{
data: dataRow
}],
}
Here is how I render the chart:
{
extends: Bar,
props: ["chartdata"],
data() {
return {
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
max: 100
}
}],
},
}
}
},
mounted() {
this.renderChart(this.chartdata, this.options)
}
}
Issue: Nothing displays and there are no errors
The bar chart only seems to work when the data in the datasets is not an array of object like:
testData: {
labels: ['test', 'test', 'test'],
datasets: [{
data: [65, 59, 80],
}]
}
After Sayf-Eddine comment, i have managed to achieve this:
I changed how i returned the chartdata like:
return {
labels: users,
datasets: dataRow
}
However, all bars are mapping to the first label
After Vitaliy Rayets comment i figured out what was wrong
i needed to return the data row like:
let dataRow = this.responses.map((d) => {
return {
label: d.user.name,
y: [d.grade],
}
});
**I changed the property 'data' to 'y' **

How can I get two stacked chart.js charts to be different types?

I have to chart.js charts that are stacked, and should be on the same x axis. How can I get the top one to be a bar chart, but the bottom one to be a line chart? I'm not sure of another way to declare 'type' other than at the top, where it affects all of the charts.
Here is an example stackbitz to the charts I'm building
https://stackblitz.com/edit/angular-chartjs-multiple-charts?file=src%2Fapp%2Fapp.component.ts
Thanks so much!
You have two individual charts, hence you should define a distinct Chart.ChartConfiguration for each. Provided that Chart.ChartOptions are the same for both charts, this could look as follows:
const chartOptions: Chart.ChartOptions = {
responsive: true,
maintainAspectRatio: false,
legend: { display: false },
scales: {
xAxes: [{ display: false }],
yAxes: [{ display: false }],
}
}
const chartConfigs: Chart.ChartConfiguration[] = [{
type: 'bar',
options: chartOptions
},{
type: 'line',
options: chartOptions
}];
And inside ngAfterViewInit, you use chartConfigs[index] to pick the appropriate chart configuration.
ngAfterViewInit() {
this.charts = this.chartElementRefs.map((chartElementRef, index) => {
const config = Object.assign({}, chartConfigs[index], { data: this.chartData[index] });
return new Chart(chartElementRef.nativeElement, config);
});
}
Please have a look at your amended StackBlitz

Firebase web keeps duplicating apexchart everytime data is updated

Hey all i am using javascript with ApexCharts to draw a chart and this chart gets its data from firebase but each time the data is changed in firebase instead of replacing the chart or updating it it appends new chart under it
this is the code
function dailyTracking(){
var query = firebase.database().ref('Facilities').on('value', function(snapshot) {
var options = {
chart: {
height: 380,
width: "100%",
type: "bar",
stacked: false
},
series: [
{
name: "Library",
data: snapshotToArray(snapshot.child('Library'))
},
{
name: "Canteen",
data: [5]
},
{
name: "Free Lab",
data: [42]
}
],
xaxis: {
labels: {
formatter: function (value, timestamp) {
return new Date() // The formatter function overrides format property
},
}
}
};
var chart = new ApexCharts(document.querySelector("#chart"), options);
chart.render();
query.off();
return snapshotToArray(snapshot);});}
I managed to solve it by adding this line
document.getElementById('chart').innerHTML = '';
before rendering the chart
Try not to wrap the chart.render() call in the event. Render the chart once and call the update event when you get new data by calling chart.updateSeries()

Chart.js not showing dynamically populated data

I was having some trouble when trying to dynamically populate bar chart in chart.js. I have two arrays, one for label, one for its price and both of them are already populated with the sorted data from firebase. Here is my code:
var ctx = document.getElementById('brandChart').getContext("2d");
var data = {
labels: [],
datasets: [{
data: [],
backgroundColor: [
"#424242",
]
}]
};
var options = {
layout: {
padding: {
top: 5
}
},
responsive: true,
legend: {
display: true,
position: 'bottom',
// disable legend onclick remove slice
onClick: null
},
animation: {
animateScale: true,
animateRotate: true
},
};
var opt = {
type: "horizontalBar",
data: data,
options: options
};
if (brandChart) brandChart.destroy();
brandChart = new Chart(ctx, opt);
// dynamically populate chart
for(var i = 0; i < labelData.length; i++){
brandChart.config.data.labels.push(labelData[i]);
}
for(var i = 0; i < priceData.length; i++){
brandChart.config.data.datasets[0].data.push(priceData[i]);
}
brandChart.update();
I managed to show all of them in bar chart, however, the result as such:
It is kind of squeeze between each labels if there are too many categories. Also, only the first bar has the color & the legends shown undefined. Any ideas how to solve these?
ɪꜱꜱᴜᴇ #1 - ꜱᴏʟᴜᴛɪᴏɴ
Add a callback for y-axis ticks, in your chart options :
options: {
scales: {
yAxes: [{
ticks: {
callback: function(t, i) {
if (!(i % 2)) return t;
}
}
}]
},
...
}
this will only show every other label on y-axis.
ɪꜱꜱᴜᴇ #2 - ꜱᴏʟᴜᴛɪᴏɴ
This is because, you have only one color in your backgroundColor array. If you want different color for each bar, then you need to populate this array with multiple color values.
Edit: as it seems form your updated question, you already kind of got the idea.
ɪꜱꜱᴜᴇ #3 - ꜱᴏʟᴜᴛɪᴏɴ
Define the label property for your dataset , like so :
datasets: [{
label: 'Legend Title', //<- define this
data: [],
backgroundColor: ["#424242", ]
}]

data and label json array not showing up on chart

I am using highcharts to display a bar chart of my data which i am getting from a json file.
I tried following highcharts example for a bar chart for some reason mine is not displaying anything on the chart nor giving me an error.
This is how i am loading my json data for labels and data values - i am returning the data that i want but the issue with display:
chartLabel: any[] = [];
chartValue: any[] = [];
this.serviceFile.getData().subscribe(
data => {
this.result = data;
this.result.forEach(graph =>{
this.chartLabel.push(graph.labelName);
this.chartValue.push(graph.value);
})
});
HTML:
<chart [options]="options"></chart>
chart options:
this.options = {
chart: {
type: 'bar',
margin: 75
},
xAxis: {
categories: this.chartLabel,
title: {
text: null
}
},
yAxis: {
min: 0,
labels: {
overflow: 'justify'
}
},
plotOptions: {
bar: {
dataLabels: {
enabled: true
}
}
},
series: [{
data: this.chartValue
}]
};
I am not sure if the way i created the arrays of my json data are appropriate for the highcharts chart.
I noticed in my console.log the way the data prints out is different which i believe is the cause of the problem and maybe some light on this matter will help:
printout for this.chartValue:
(3)[12,34,54]
what this should look like is:
12,34,54

Categories