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()
Related
I have been trying to create a scatter graph using chart.js, and using data from a JSON object I am fetching from a public api, however my graph is not being created but I am not getting any errors on my console therefore I am unsure as to where the problem is.
This is the structure of my JSON object
0:{
first_name: "Shkodran"
form: "2.3"
points_per_game: "3.2"
now_cost: 51
second_name: "Mustafi"
web_name: "Mustafi"
minutes: 620
goals_scored: 0
assists: 2
clean_sheets: 2
goals_conceded: 9
}
Each entry is a different player and there are 628 entries.
Below is the code I am using
Fetching the public api and parsing the response
var request = new XMLHttpRequest()
var json;
request.open('GET','https://cors- anywhere.herokuapp.com/https://fantasy.premierleague.com/api/bootstrap-static/' , true)
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
json = JSON.parse(this.response);
}
console.log(json);
}
request.send();
Generating the datasets for the scatter graph as I want my graph to be x:now_cost and y:points_per_game.
Creating the chart using chart.js
if (document.readyState === 'complete') {
function generateData() {
var data=[];
json.elements.forEach(elements => {
data.push({
x: elements.now_cost,
y: points_per_game
});
});
return data;
}
var ctx = document.getElementById('chart1').getContext('2d');
var scatterChart = new Chart(ctx, {
type: 'scatter',
data: {
dataset: [{
data: generateData()
}]
},
options: {
title: {
display: true,
text: 'Cost vs Points Per Game Chart'
},
scales: {
xAxes: [{
title:{
display:true,
text: 'Cost'
},
type: 'linear',
position: 'bottom'
}],
yAxes: [{
title:{
display:true,
text: 'Points Per Game'
},
type: 'linear',
position: 'bottom'
}]
}
}
});
}
Your data is not of valid JSON format, individual properties need to be separated by a comma each. There's also an error inside the generateData function with the assignment to the y property. It should be rewritten as follows:
function generateData() {
var data = [];
json.elements.forEach(element => {
data.push({
x: element.now_cost,
y: element.points_per_game
});
});
return data;
}
Or you could even get rid of this function generateData and assign data directly as follows:
dataset: [{
data: json.elements.map(e => ({ x: e.now_cost, y: e.points_per_game }))
}]
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);
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
I'm a complete newb with js and jquery but have muddled my way through getting a chart to properly display using Flask and an Ajax request. Where I'm having a problem is getting the charts data to refresh. I can get the chart to display just fine if I create it as a new chart as shown in the code below
$(document).ready(function() {
var getdata = $.post('/charts');
var ctx = document.getElementById('myChart').getContext('2d');
var myChart
getdata.done(function(results){
var chartData = {
labels: results['month'],
datasets: [{
label: 'Debits',
data: results['debit'],
backgroundColor: "rgba(153,255,51,0.4)"
}, {
label: 'Credits',
data: results['credit'],
backgroundColor: "rgba(255,153,0,0.4)"
}, {
label: 'Balance',
data: results['balance'],
backgroundColor: "rgba(50,110,0,0.4)"
}]
}
myChart = new Chart(ctx, {type: 'line', data: chartData});
});
$("form :input").change(function() {
year = $(this).val();
console.log(year)
$.ajax({
type: "POST",
url: "/data",
data: {'year':year},
success: function(results){
var updatedData = {
labels : results['month'],
datasets : [{
label: 'Debits',
data: results['debit'],
backgroundColor: "rgba(153,255,51,0.4)"
}, {
label: 'Credits',
data: results['credit'],
backgroundColor: "rgba(255,153,0,0.4)"
}, {
label: 'Balance',
data: results['balance'],
backgroundColor: "rgba(50,110,0,0.4)"
}]
}
myChart= new Chart(ctx, {type: 'line', data: updatedData});
}
});
});
});
But if I change the last line to
myChart.update(updatedData)
nothing happens, I don't get any errors, the chart doesn't update. Nothing. The strange thing is that I know the myChart is global because I don't have to create it again after the Ajax request.
Thanks
From the documentation of charts.js (http://www.chartjs.org/docs/#getting-started-creating-a-chart), you first need to change data and then call update (arguments for update function are not the data, but duration etc.):
.update(duration, lazy)
Triggers an update of the chart. This can be safely called after replacing the entire data object. This will update all scales, legends, and then re-render the chart.
// duration is the time for the animation of the redraw in milliseconds
// lazy is a boolean. if true, the animation can be interrupted by other animations
myLineChart.data.datasets[0].data[2] = 50; // Would update the first dataset's value of 'March' to be 50
myLineChart.update(); // Calling update now animates the position of March from 90 to 50.
So in your case:
myChart.data = updatedData;
myChart.update();
I am new to using HighCharts and JSON. I am pulling data from my database and it is producing the following JSON:
{"GS10":[{"data_date":-528656400,"value":2.83},{"data_date":-526064400,"value":3.05},{"data_date":-523386000,"value":3.11},{"data_date":-520794000,"value":2.93},{"data_date":-518115600,"value":2.95},{"data_date":-515437200,"value":2.87},{"data_date":-512845200,"value":2.66},{"data_date":-510166800,"value":2.68},{"data_date":-507574800,"value":2.59},{"data_date":-504896400,"value":2.48},{"data_date":-502218000,"value":2.47},{"data_date":-499798800,"value":2.37},{"data_date":-497120400,"value":2.29},{"data_date":-494528400,"value":2.37},{"data_date":-491850000,"value":2.38},{"data_date":-489258000,"value":2.3},{"data_date":-486579600,"value":2.36},{"data_date":-483901200,"value":2.38}]}
This JSON is then to be rendered into a line chart using HighCharts. The script is below. It renders a graph, but the graph is blank. I am currently only testing with one series, but the intent is to be able to use multiple series once I can successfully graph one. Any help would be appreciated, thanks.
<script>
$(function () {
var test_point = 'GS10';
$(document).ready(function() {
$.getJSON("get_data.php", function(json) {
var seriesArr = [];
var series = {
name: test_point,
data: []
};
$.each(json[test_point], function(key, data){
series.data.push({
date: data.data_date,
value: data.value
});
});
seriesArr.push(series);
var options = {
chart: {
renderTo: 'container',
defaultSeriesType: 'line'
},
xAxis: {
type: 'datetime'
},
series: seriesArr
};
var chart = new Highcharts.Chart(options);
});
});
});
</script>
The problem is with that part:
series.data.push({
date: data.data_date,
value: data.value
});
It shouldn't be data/value but rather x/y:
series.data.push({
x: data.data_date,
y: data.value
});