I'm using .NET MVC. Currently I have a data set that fills in points for a JS chart. Currently, I have static data(numbers) in the data property of the data set. I'm looking for idea's, tutorials, how-to's, on how to fill the data property with data from my SQL DB. I've looked all over and see numerous tutorials with static data like I have.
var ctx2 = document.getElementById("totalSpendingChart");
var data2 = {
datasets: [{
label: "Spending",
data: [8,10,11,15], /* THIS.. how do I get SQL data here? */
borderColor: "#e8144d"
}],
labels: [ "2017", "2018", "2019"]
};
var LinChart1 = new Chart(ctx2, {
type: "line", data: data2, options: {
pointStyle: "circle",
legend: { display: false },
scales: { yAxes: [{ display: true, gridLines: { display: true } }], xAxes: [{ display: false, gridLines: { display: false } }] }
}
});
You somehow need to get the data from the backend (SQL) to the frontend (JavaScript).
Option 1
You could inject the data into your template (before you render the chart). For example by serializing your data to JSON and parse it using javascript:
<script>
var chartData = JSON.parse(<%= DataSet %>);
</script>
Option 2
You could create an endpoint (url to fetch the data from) which can be used in javascript with an ajax get request. Once the data is loaded you can render the chart:
$.ajax("https://your-endpoint-to-fetch-the-data")
.done(renderChart);
function renderChart(data) {
var ctx = document.getElementById("totalSpendingChart");
var chartData = {
datasets: [{
data: data,
// ...
}]
};
var lineChart = new Chart(ctx, {
// ...
});
};
(this example uses jQuery for the ajax part)
Related
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' **
I have been trying many ways to push the collection of array into the dataset.
Anyone can help me to push an array into stacked chart based on the codepen below?
Here's the example
Codepen stacked bar
Javascript
const getData = ()=>new Array(7).fill('').map(v=>randomScalingFactor());
var barChartData = {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'Dataset 1',
backgroundColor: window.chartColors.red,
data: getData()
}, {
label: 'Dataset 2',
backgroundColor: window.chartColors.blue,
data: getData()
}, {
label: 'Dataset 3',
backgroundColor: window.chartColors.green,
data: getData()
}]
};
var ctx = document.getElementById('canvas').getContext('2d');
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
title: {
display: true,
text: 'Chart.js Bar Chart - Stacked'
},
tooltips: {
mode: 'index',
intersect: false
},
responsive: true,
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [{
stacked: true
}]
}
}
});
document.getElementById('randomizeData').addEventListener('click', function() {
barChartData.datasets.forEach(dataset=>{
dataset.data = getData();
});
window.myBar.update();
});
Here's the data for arrays
The issues should be the dataset with different colors and total should be the value for Y axis and there should be another collection of array date for X axis and the colors for the dataset should be different. The data for issues and total will be retrieved from Mysql database.
I am using laravel and the table above was achieved using foreach loop.
You really should provide more information. What have you tried, what failed...
Don't expect people do your job, wasting their time so you can nap for an hour. StackOverflow is for specific questions and not for letting others do somebody else's work. And getting data for chart.js is something trivial you can find in any other post about chart.js.
Enough ranting, just letting you know you shouldn't expect answers in the future for questions like that.
The code you posted in your question is quite different to the one from the codepen link, but this can be due to Narendra Jadhav's 'update'. But if confused me enough so I don't know what you want.
You didn't stated if you want to update our data so I didn't implemented updating.
Don't know the use case of this random randomizeData() does, especially with the fixed length of 7. I changed it but as I don't know the reason it may be different to your use case.
I don't know the data format you get from MySQL so I used a possible format. Same as above, could be different to what you want.
Please use an newer version of chart.js and not a year old version. There are no breaking changes, only improvements. Just updating the version eliminated a few bugs, e.g. the strange space between the yAxis and the chart.
Complete code (same as JSBin):
var initialData = [
{
'Barcode Sticker Problem':1,
'Extra':1,
'Labelling Problem':2,
'Stock Accuracy':1,
'Wrong Quality':1
},{
'Barcode Sticker Problem':1,
'Extra':1,
'Labelling Problem':2,
'Stock Accuracy':1,
'Wrong Quality':3
},
{
'Barcode Sticker Problem':2,
'Extra':2,
'Labelling Problem':1,
'Stock Accuracy':2,
'Wrong Quality':3
}
]
const colors = [
'red',
'blue',
'green'
]
var barChartData = {
labels: Object.keys(initialData[0]),
datasets: []
};
for (var i = 0; i < initialData.length; i++) {
barChartData.datasets.push(
{
label: 'Dataset ' + (i+1),
backgroundColor: colors[i % colors.length],
data: Object.values(initialData[i])
}
)
}
var barChartOptions = {
title: {
display: false,
text: 'Chart.js Stacked Bar Chart'
},
tooltips: {
mode: 'index',
intersect: false
},
responsive: true,
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [{
stacked: true,
ticks: {
precision: 0
}
}]
}
}
var ctx = document.getElementById('canvas').getContext('2d');
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: barChartOptions
});
document.getElementById('randomizeData').addEventListener('click', function() {
barChartData.datasets.forEach(dataset=>{
var newData = []
for (var i = 0; i < dataset.data.length; i++) {
newData.push(Math.floor(Math.random()*3)+1)
}
dataset.data = newData
});
window.myBar.update();
});
Im using chartJs library to create a simple line chart. Problem is that when i have the data in a array and trying to insert it nothing is showing, no error given. if i type in the data it shows correctly.
Manually enter data works but not when in a array.
strProdChart1 = '"2019-09-16","2019-09-17"|5,4';
arrProdChart1 = strProdChart1.split("|");
console.log(arrProdChart1[1]);
var objProdChart1 = document.getElementById('ProdChart1');
ProdChart1 = new Chart( objProdChart1, {
type: "line",
data: {"labels": [arrProdChart1[0]],"datasets": [{"label": "test", "data": arrProdChart1[1] ,"borderWidth": 1,"backgroundColor": "red"}]},
options: {
color: 'red',
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
the array containes labels and the amounts, getting labels works "arrProdChart1[0]" but when i want to insert the numbers with "arrProdChart1[1]" nothing is showing in the chart. Cant see what i do wrong, if instead replace arrProdChart1[1] with the acctual numbers "5,4" it works fine.
print to the console shows numbers "5,4"
thanks
The data is expecting an array but ur arrProdChart1[1] is not an array
so convert ur arrProdChart1[1] variable to an array
strProdChart1 = '"2019-09-16","2019-09-17"|5,4';
arrProdChart1 = strProdChart1.split("|");
console.log(arrProdChart1[1]);
var newAR = arrProdChart1[1].split(",")
var objProdChart1 = document.getElementById('ProdChart1');
ProdChart1 = new Chart( objProdChart1, {
type: "line",
data: {"labels": [arrProdChart1[0]],"datasets": [{"label": "test", "data": newAR ,"borderWidth": 1,"backgroundColor": "red"}]},
options: {
color: 'red',
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
Hope Fully It help
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()
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