using array values in chart.js data and label field - javascript

I wish to pass values of an array to the data and label fields of the chart.js dataset.
Here the code from success of ajax call made to fetch json data. I fetch the json data and store it into an array.
Data = jQuery.parseJSON(result);
var count = Data.length;
var counter = 0;
while(count > 0) {
LabelResult[counter] =[Data[counter].TIME];
counter++;
count --;
}
Now i wish to use this label values into the labels filed.
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: [LabelResult],
datasets: [{
label: '# of Votes',
data: [DataResult],
borderWidth: 1
}]
}
});
But there seems some issue and the data is not getting rendered on the chart

LabelResult is an array, change
labels: [LabelResult]
to
labels: LabelResult
Also:
data: [DataResult]
to
data: DataResult
Like:
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: LabelResult,
datasets: [{
label: '# of Votes',
data: DataResult,
borderWidth: 1
}]
}
});

I think you could try to remove some brackets.
while(count > 0){
LabelResult[counter] = Data[counter].TIME; // here removed brackets
counter++;
count --;
}
and
data: {
labels: LabelResult, // here removed brackets
datasets: [{
label: '# of Votes',
data: DataResult, // here removed brackets
borderWidth: 1
}]
},
I hope that will works.

Related

Passing data to a chart javascript object and array

What is the best approach to display the data in a chart?
To begin, my application has an empty array that receives objects.
// location where the users are storage
let usersList = [];
// these are the information from an user
const newUser = {
name:`${user.name.first} ${user.name.last}`,
social: Math.floor(Math.random() * 1000 )
}
So, by the end of my code, I have the chart, everything is working but with dummy data.
const myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'], // should get the usersList.name
datasets: [{
label: ' Views per channel ',
data: [12, 10, 3, 5, 2, 3], // // should get the usersList.social
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
Ideally, I would need to change the labels to have the name of each user, and the data to have the social of each user. My initial thought was a for loop, but I remember that ES6 has array destructuring.
I am not sure how to approach the problem, do you have any insight?
Thank you very much.
You can use the Array.map() method on the usersList to create the arrays that contain the desired attributes of the users.
Your code would have to be changed as follows:
data: {
labels: usersList.map(u => u.name),
datasets: [{
label: ' Views per channel ',
data: usersList.map(u => u.social),
borderWidth: 1
}]
}

How to replace the data array of my ChartJS

I am doing a project where I need to be able to change the data array of a chart with a totally different one. My code is working for the labels of the chart, but the data is not changing, and I dont understand why. Hope you can help me, thanks in advance.
Here is my code :
var label = [];
var testArray= [{"production":"12","mois":"janvier"},{"production":"5","mois":"février"},{"production":"9","mois":"mars"},{"production":"17","mois":"avril"},{"production":"6","mois":"mai"},{"production":"8","mois":"juin"},{"production":"17","mois":"juillet"},{"production":"7","mois":"aout"},{"production":"10","mois":"septembre"}];
var chartData = {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [7, 4, 3, 5, 2, 3]
}]
};
var newdata = [];
function updateData(){
chartData.datasets.data = testArray.map(function (item) {
return item.production;
});
chartData.labels = testArray.map(function (item) {
return item.mois;
});
graphique.destroy();
graphInit();
}
function graphInit() {
graphique = new Chart(ctx, {
type: 'bar',
data: chartData,
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
Inside function updateData, you need to access the data with chartData.datasets[0].data. Further you should update data with an array of number instead of string. Use Number to convert string to number as follows:
chartData.datasets[0].data = testArray.map(function (item) {
return Number(item.production);
});
this can also be written in a simpler way:
chartData.datasets[0].data = testArray.map(item => Number(item.production));
Also instead of graphique.destroy() and graphInit() you can simply use graphique.update(). Maybe this answer is of some further help too: https://stackoverflow.com/a/60091960/2358409.

Inserting data from controller to an array in javascript

I try to create a graph using Chart.js and get the data from database, but I am confused how to pass the data to an array variable in view.
This is the Controller
public function ApiLaporanBulanan()
{
$data = DB::table("transaksipenjualan")->select(DB::raw('EXTRACT(MONTH FROM tanggaltransaksi) AS Bulan, SUM(total) as Pendapatan'))
->groupBy(DB::raw('EXTRACT(MONTH FROM tanggaltransaksi)'))
->get();
return response()->json($data);
//Accessing Data
dd($data[0]->Bulan);
}
This is the script in view
<script>
var url = "{{url('laporan/pendapatanAPI')}}";
var Bulan = [];
var Pendapatan = [];
$(document).ready(function(){
$.get(url, function(response){
response.forEach(function(data){
Bulan.push(data->Bulan);
Pendapatan.push(data->Pendapatan);
});
var ctx = document.getElementById("canvas").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: Bulan,
datasets: [{
label: 'Nilai Pendapatan',
data: Pendapatan,
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
});
});
</script>
You can create two array in your controller.
$label = [];
$dataset = [];
and loop through your collection and push data to these arrays
foreach($data as $value){
$label[] = $value->data_field;
$dataset[] = $value->data_field;
}
And pass it to your blade and assign these array to your chart
...
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: Bulan,
datasets: [{
label: 'Nilai Pendapatan',// label data
data: Pendapatan, // dataset
borderWidth: 1
}]
},
....

How to display grouped data in ChartJs

I have the following array:
Where the arrays keys are the dates and the only element I want to plot, of each set, is the weight. Look:
I am putting the code as follows. Notice that I am already grouping in the date attribute the whole set belonging to each that key.
var ctx = document.getElementById("barChart").getContext("2d");
var data = {
labels: ['21/03/2018','01/04/2018','02/04/2018','04/04/2018','05/04/2018','06/04/2018'],
datasets: [
{
label: '21/03/2018',
data: [12, 0, 0]
},
{
label: '01/04/2018',
data: [15.00, 15.00,15.00]
},
{
label: '02/04/2018',
data: [25.00, 25.00, 25.00]
},
{
label: '04/04/2018',
data: [25.00, 25.00, 25.00]
},
{
label: '05/04/2018',
data: [-8.14,-7.93, -7.84]
},
{
label: '06/04/2018',
data: [-35.9 ,-38.1, -37.5]
},
]
};
var myBarChart = new Chart(ctx, {
type: 'bar',
data: data,
});
But in this way ChartJs does not understand that it only needs to plot the data set present in the "data" attribute and grouping them by the key. Plotting the graph in the wrong way.
How could I plot the data correctly knowing that they are already grouped?
You need to organize your data as such:
var ctx = document.getElementById("canvas").getContext("2d");
var data = {
labels: ['21/03/2018','01/04/2018','02/04/2018','04/04/2018','05/04/2018','06/04/2018'],
datasets: [
{
data: [12, 15.00, 25.00, 25.00, -8.14, -35.9]
},{
data: [0, 15.00, 25.00, 25.00, -7.93, -38.1]
},{
data: [0, 15.00, 25.00, 25.00, -7.84, -37.5]
}
]
};
var myBarChart = new Chart(ctx, {
type: 'bar',
data: data,
options:{
legend: 'none'
}
});
I took your legend out as it's useless in this case. To look at it in the coding persepective, whatever index the date in labels is at needs to correlate with the index of the information you want to display in that grouping. data[0] refers to labels[0] and so on.

Chart.js t.ticks.map is not a function

Both results and labels come from the server but they seem alright. When I run this code I don't get any graphics. I'm using the chart.js from the CDN.
EDIT: Clarification, both results and data come from the code. They are not hardcoded as they look in the example.
The errors I get say:
t.ticks.map is not a function
Unable to get property 'skip' of undefined or null reference
The code:
<canvas id="myChart" width="400" height="400"></canvas>
var ctx = document.getElementById("myChart").getContext("2d");
var result = [0, 0, 0];
var lbls = ['A', 'B', 'C'];
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: lbls.split(','),
datasets: [{
label: '# of Votes',
data: result
}]
}
});
Any suggestion about another chart utility is welcome too.
The labels requires a array variable but the var lbls = $('#lbls').html() returns a string so splitting it with ',' will do the job
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: lbls.split(','),
datasets: [{
label: '# of Votes',
data: [20, 10]
}]
}
});

Categories