I’m trying to pass my data to the graph but it won't work. If I add numbers to it manually like
data: [1,2,3]
Than it works. In my code you'll see that I console.logged my data.weight and data.goal. They appear in the console as they should.
Here's the code:
var endpoint = '/api/data';
var defaultDataW = [];
var defaultDataG = [];
$.ajax({
method: 'GET',
url: endpoint,
success: function(data){
console.log(data.weight);
console.log(data.goal);
defaultDataW = data.weight;
defaultDataG = data.goal;
var graph = document.getElementById("weight-graph");
Chart.defaults.global.defaultFontFamily = "Lato";
Chart.defaults.global.defaultFontSize = 18;
var dataFirst = {
label: "Your Weight (Kg)",
data: defaultDataW,
lineTension: 0,
fill: false,
borderColor: 'red'
};
var dataSecond = {
label: "Your Goal (Kg)",
data: defaultDataG,
lineTension: 0,
fill: false,
borderColor: 'blue'
};
var DateData = {
labels: [], //Dates will be here
datasets: [dataFirst, dataSecond]
};
var chartOptions = {
legend: {
display: true,
position: 'top',
labels: {
boxWidth: 80,
fontColor: 'black'
}
}
};
var lineChart = new Chart(graph, {
type: 'line',
data: DateData,
options: chartOptions
});
},
error: function(error_data){
console.log("Error");
console.log(error_data);
}
})
})
You are doing most everything right, but you are changing 'type' of the data.....
what you are doing RIGHT
var defaultDataW = [];
This sets the data to an ARRAY.
Though, in the ajax, you are doing this:
defaultDataW = data.weight;
Which, by your other comments, clearly says that 'data.weight' is an INTEGER.
So, when you try to use that (now INTEGER) as data in a Chart
data: defaultDataW,
It doesn't work (and, no surprise......)
Chart.js requires an ARRAY (at minimum) to work - https://www.chartjs.org/docs/master/general/data-structures/
Now, how can you fix this?????
Pretty simple......
In your ajax, change
defaultDataW = data.weight;
To ADD to the ARRAY (instead of replacing the array with an integer....)
defaultDataW.push(data.weight);
In case you add other code later (or for future projects, putting things in a function, etc....), you might want to also learn about a way to CLEAR that array. It doesn't hurt to do it now, though the way your code is it really should not be needed. I'm including it here for others to reference, etc.
Before doing a 'push' (certainly if you are doing a loop, etc.), you may need to clear the array first, like this:
defaultDataW.length = 0;
This will empty the array and then you can 'push' what you really want in there. If the array is not empty and you push, then you will have the old data as well as the new (of course, depending on what you are doing, that may be a good thing - though in this case, it is not)
Related
I'm trying to display a chart in apexcharts, and use a variable as the data. When I do this, nothing is displayed. See the following:
var message = '[1,4]'
var options = {
chart: {
type: 'line',
sparkline: {
enabled: true,
}
},
series: [{
data: message,
}],
}
var chart = new ApexCharts(document.querySelector("#chart"), options);
chart.render();
Using the variable message as data doesn't work. When I switch the line:
data: message,
to
data: [1,4]
it displays correctly. However, I must use a variable. How do I do this?
You declared message variable as STRING, It is expecting an ARRAY
Please change
var message = '[1,4]'
to
var message = [1,4];
I am trying to get JSON from Poloniex's public API method (specifically the returnChartData method) to display chart history of cryptocurrencies against one another into a Highchart Stockchart graph (looking like the demo one here.).
This is part of my JavaScript code to use the Poloniex returnChartData callback, get the JSON from it and implement it into the 'data' segment of the chart. So far it is not working and I can't for the life of me figure out what I need to change.
var poloniexUrl = "https://poloniex.com/public?command=returnChartData¤cyPair=BTC_XMR&start=1405699200&end=9999999999&period=14400";
$.getJSON(poloniexUrl, function(data){
results = data;
});
// Creates Chart
var chart = new Highcharts.StockChart({
chart: {
renderTo: 'cryptoChart',
backgroundColor: 'white'
},
title: {
text: currentTitle
},
series: [{
data: results,
turboThreshold: 1000
}],
xAxis: {
original: false
},
rangeSelector: {
selected: 1
},
plotOptions: {
line: {
gapSize: 2
}
}
});
Would love any help!
Refer to this live demo: http://jsfiddle.net/kkulig/0f4odg5q/
If you use turboThreshold the points' options need to be given as an integer or an array (Explanation: https://api.highcharts.com/highstock/plotOptions.series.turboThreshold). In your case the format is JSON, so I disabled turboThreshold to prevent Higcharts error 12 (https://www.highcharts.com/errors/12):
turboThreshold: 0
$.getJSON is asynchronous - the best way to make sure that data variable is initialized is using it inside callback function (second argument of getJSON):
$.getJSON(poloniexUrl, function(data) {
// Creates Chart
var chart = new Highcharts.StockChart({
chart: {
(...)
The data that you fetch looks like candlestick series - I changed the type of the series:
type: 'candlestick'
Date will be properly understood by Highcharts if it's kept in the x property of JSON object (not date):
data: data.map((p) => {
p.x = p.date;
return p
}),
I have a strange issue occurring with my Charts.js line chart.
Upon page load, nothing seems to be visible in the <canvas> element:
However, once you resize the browser window, the chart displays as intended:
Has anyone else encountered this issue and know of a way to fix it?
The JavaScript for my chart is below. Please let me know if I need to alter it in any way to fix this issue.
function drawLineChart() {
var dates = [];
var clientCosts = [];
$.ajax({
url: '../inc/wip-data.php',
dataType: 'json'
}).done(function(data) {
data.forEach(function(item) {
dates.push(item.date);
clientCosts.push(item.clientCostsTotal);
});
});
console.log(dates, clientCosts);
var chartData = {
labels: dates,
datasets: [{
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
pointHighlightStroke: "rgba(151,187,205,1)",
data: clientCosts
}]
};
// Get the context of the canvas element we want to select
var ctx = document.getElementById("myChart").getContext("2d");
// Instantiate a new chart
var myChart = new Chart(ctx, {
responsive: true,
type: 'line',
data: chartData,
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
drawLineChart();
This issue is not replicating in JS Bin. The only difference between the JS Bin and my local build is the AJAX call for the data, so that leads me to believe the AJAX call is what is causing the issue. Any guidance on what may be calling this issue would be appreciated.
The data used by the chart is not available when the chart is created. This is because the ajax call is asynch, and the data becomes available only when the ajax request is complete.
In order to have the chart visible right away, you will need to use this call myChart.update(), in the "done" function of the ajax call after you populate the data, in order to update the chart:
...
data.forEach(function(item) {
dates.push(item.date);
clientCosts.push(item.clientCostsTotal);
});
myChart.update();
I am ajax calling a php script that outputs two data points
[epoch data, cpu]
I would like to be able to create highchart guage chart and display cpu utilization and as a data lable, I like to display the time that I get from the php call.
function request_cpu_Data() {
$.ajax({
url: 'get_cpu.php',
success: function(data) {
var myObj = JSON.parse(data);
var point = cpu_chart.series[0].points[0];
var point1 = cpu_chart.series[1].points[0];
var newVal=myObj[1];
var newVal1=myObj[0];
point.update(newVal);
point1.update(newVal1);
setTimeout(request_cpu_Data, 10000000);
},
cache: false
});
}
my series options are like this:
series: [{
name: 'CPU',
data: [0]
},{
name: 'Date',
data: []
}
]
I am getting this error:
Uncaught TypeError: Cannot call method 'update' of undefined
Is this how you set up the second series?
var point1 = cpu_chart.series[1].points[0];
Your second series contains no data, so your cpu_chart.series[1].points is an empty array.
You must use setData if data.lenght === 0, like this:
var secondSeries = chart.series[1];
if (secondSeries.data.length === 0) {
secondSeries.setData([newValue]);
} else {
secondSeries.points[0].update(newValue);
}
I hope that will help you.
In flot, how can I create a pie chart where each wedge is a link to a different web-page?
I gave it a shot, but I wasn't able to do it. I started with this example, then added:
grid: { clickable: true },
right above the "pie: {" line. Then I added a plotclick function at the end:
$("#placeholder").bind("plotclick", function (event, pos, item) {
alert('click!');
for(var i in item){
alert('my '+i+' = '+ item[i]);
}
});
You'll see the "click!" message, but "item" has no properties.
I was thinking you'd just add URLs to the data ojects, then forward the browser to the appropriate URL from within the plotclick function. If you figure it out, I'd be interested to know!
Update: Here's something that might work -- it just turns the labels into links. Put the URLs in your data like this:
$.plot($("#placeholder"), [
{ label: "Serie1", data: 10, url: "http://stackoverflow.com"},
{ label: "Serie2", data: 30, url: "http://serverfault.com"},
{ label: "Serie3", data: 90, url: "http://superuser.com"},
{ label: "Serie4", data: 70, url: "http://www.google.com"},
{ label: "Serie5", data: 80, url: "http://www.oprah.com"},
{ label: "Serie6", data: 110, url: "http://www.realultimatepower.net/"}
],
Then set the labelFormatter to something like:
return ''+serie.label+'<br/>'+Math.round(serie.percent)+'%';
Clicking in the pie wedges themselves still does nothing special, though.
I know this is an old thread but I have discovered another way of doing this.
Make sure grid is set to clickable
var data = [{
"label" : "series1",
"data" : 24,
"url" : "http://stackoverflow.com"
},
{
// etc etc
}];
$.plot($('.chart'), data, function() {
// Your options
grid: {
clickable:true
}
});
Bind a click function to the element and use javascript to redirect to the url.
$('.chart').bind("plotclick", function(event,pos,obj) {
window.location.replace(data[obj.seriesIndex].url);
});
Adding to the answer by Derek Kurth...
It looks like flot is ignoring any additional objects that we include in the JSON. For example when I used
data: [10, 0, "http://stackoverflow.com"]
// 0 is used as an intercept value for y-axis
it worked without any trouble and I was able to access the data from the event handler like
$("#placeholder").bind("plotclick", function (event, pos, item) {
alert(item.series.data);
});
I am new to this flot library and not great at JavaScript. So probably this is not the right way to do things but it works. I have always felt that embedding additional information in UI elements in HTML is a pain :(