How to make Highcharts fetch data from external JSON file? - javascript

Basically, I have this http://jsfiddle.net/TWF6N/
Instead of having the data series in the JS file, I want to have the JS retrieve a JSON file.
I do not want this to be in the JS file:
data = {"aaData": [
[1, "70.1700", "2008-12-29 11:23:00"],
[2, "70.2600", "2008-12-29 16:22:00"],
[3, "70.6500", "2008-12-30 11:30:00"],
[4, "70.8700", "2008-12-30 16:10:00"],
[5, "70.5500", "2009-01-02 11:09:00"],
[6, "70.6400", "2009-01-02 16:15:00"]
]};
How do I make this?
Thank you.

Straight from the HighChart documentation:
Your JSON data would look like this:
[
[1, "70.1700", "2008-12-29 11:23:00"],
[2, "70.2600", "2008-12-29 16:22:00"],
[3, "70.6500", "2008-12-30 11:30:00"],
[4, "70.8700", "2008-12-30 16:10:00"],
[5, "70.5500", "2009-01-02 11:09:00"],
[6, "70.6400", "2009-01-02 16:15:00"]
]
And your JS would look something like this:
$(function () {
var chart;
$.getJSON('data.json', function(jsonData) {
chartOptions.series = jsonData;
chart = new Highcharts.Chart(chartOptions);
});
var chartOptions = {
chart: {
renderTo: 'container'
},
xAxis: {
type: 'datetime'
},
series: []
};
});

Presumably you're using some server side technology like php or asp.net? If so, then you could just make a call back to the server to receive your json in a HttpResponse.

Related

how to transform changing data to be visualized in a chart.js

I am using a url to fetch data that constantly updates and changes. It comes back in the form of an array like this:
[[0,14],[1,11],[2,15],[3,12],[4,8],[5,8],[6,9],[7,9],[8,9],[9,7]].
I would like this to be transformed so I can use it in a chart.js
I think I should convert it to a json file, but don't really know how it works because the fetch needs to be initialized every 5 seconds and that new data has to be put in the json file every time and then displayed in the chart.js.
I got the data in the updatingArray[], but i'm stuck now.
function getDataFromDatapointsUrl(){
const proxyurl = "https://cors-anywhere.herokuapp.com/";
const url = 'https://canvasjs.com/services/data/datapoints.php)';
fetch(proxyurl + url)
.then(response => response.text())
.then(contents => createArrayForUpdatingData(contents));
}
getDataFromDatapointsUrl();
// setInterval(getDataFromDatapointsUrl, 500);
var updatingDataArray = [];
function createArrayForUpdatingData(updatingData){
updatingDataArray.push(updatingData);
}
I would like the data from the array to be split up in the chart.
[[0,14],[1,11],[2,15],[3,12],[4,8],[5,8],[6,9],[7,9],[8,9],[9,7]].
So the 0,1,2,3,4,5,6,... should become the x-axis and the 14,11,15, ... should become the value of the chart-line, bar-, pie, whatever you like it to visualized like.
Based on your example you can simply iterate updatingDataArray and push each value to a separate array that you then pass to Chart.js:
var updatingDataArray = [
[0, 14],
[1, 11],
[2, 15],
[3, 12],
[4, 8],
[5, 8],
[6, 9],
[7, 9],
[8, 9],
[9, 7]
];
var labels = [],
values = [];
updatingDataArray.forEach(function(val, idx) {
labels.push(val[0]);
values.push(val[1]);
});
new Chart(document.getElementById("chart"), {
type: "line",
data: {
labels: labels,
datasets: [{
data: values
}]
},
options: {}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<canvas id="chart"></canvas>

Using context variables as javascript parameters

I'm working on a project in Django, for part of it I'm trying to use Googles chart api, which uses a Javascript function to plot the graph. So what I'm trying to do is generate the graph data in my views.py and then pass the data through the context variables to the script. To test this I tried to do:
graphplot = [['Age', 'Weight'],[ 8, 12],[ 4, 5.5],[ 11, 14],[ 4, 5],[ 3, 3.5],[ 6.5, 7]]
context = {
"graphplot": graphplot,
}
in my views.py then I have:
var data = google.visualization.arrayToDataTable({{graphplot}});
in my template, however this doesn't seem to work.
When I do:
var data = google.visualization.arrayToDataTable([
['Age', 'Weight'],
[ 8, 12],
[ 4, 5.5],
[ 11, 14],
[ 4, 5],
[ 3, 3.5],
[ 6.5, 7]
]);
It does show the graph so I know it's not a problem with the JavaScript.
Any help would be appreciated
Try this, It should work.
var plot_data = {{graphplot}};
var data = google.visualization.arrayToDataTable(plot_data);

data parsing using a csv file in d3

consider the example shown in the link Labeling the axis with alphanumeric characters. Is this the correct way to parse var data?
var data = []
d3.csv("data.csv", function(data) {
data = data.forEach(function(d) { return [ x[d[0]], y[d[1]]] });
console.log(data)
});
data.csv should hold these values
[2, 2],
[3, 3],
[4, 4],
[5, 4],
[5.5, 5],
[6, 6],
[6, 7],
[6.5, 8],
[6.5, 16],
[17, 16]
Assuming that you meant that data should hold those values, your data.csv should look like the following:
first,second
2,2
3,3
4,4
5,4
5.5,5
6,6
6,7
6.5,8
6.5,16
17,16
And then you can parse it using the names of the fields:
var data = []
d3.csv("data.csv", function(csvData) {
// By default, all the values read are treated as strings.
// So have to make them numbers explicitly
data = csvData.forEach(function(d) { return [ +d.first, +d.second ] });
console.log(data);
// Draw the chart here.
});

How to change calculation on nv3d when switching to stacked?

I'm using d3.js and nvd3.js to display some data from different datasets. One of the sets (A) contains the absolute number of orders, the other set (B) contains the number of orders from new customers, such that A >= B for every position. Example:
[{
key : 'orders',
values: [[1, 10], [2, 5], [3, 8], ...]
},{
key : 'orders by new customers',
values: [[1, 4], [2, 0], [3, 4], ...]
}]
I'd like to use a stacked multibar chart to display those series. In "Grouped" view, everything works nicely and I have both bars grouped beneath each other. However, when I switch to "Stacked" mode I was expecting, that the overall number does not change. It appeared that nv3d.js is then adding up both values and i get a new overall value.
Is there a way to change the calculation when switching to stacked mode? I was digging through the source code, but could not find a usable method to achieve this.
Thanks in advance!
If I understood your problem correctly, it would make more sense to restructure your data to make it conceptually match with bars being 'stacked' (which implies two values being added together), to something like this where:
orders = recurring orders + orders by new customers
[{
key : 'recurring orders',
values: [[0, 6], [0, 5], [0, 4], ...]
},{
key : 'orders by new customers',
values: [[1, 4], [2, 0], [3, 4], ...]
}]

Plot the json array using jquery flot

var data =[ { label: "Foo", data: [ ["2012-09-01", 1], ["2012-10-01", -14], ["2012-11-01", 5] ] },
{ label: "Bar", data: [ ["2012-09-01", 13], ["2012-10-01", 11], ["2012-11-01", -7] ] }
];
var options = {
series: {
lines: { show: true },
points: { show: true }
}
};
<div id="placeholder"></div>
<script>
$.plot($('#placeholder'), data, options);
</script>
I am confused why the graph is not getting plotted with the data. Ignore my novice knowledge on flot. Can anyone give me an idea how i should be able to do it.
Are you sure flot can handle values formatted as strings? You should probably convert the strings to real dates or milliseconds...
You can use the moment.js library:
var data =[ { label: "Foo", data: [ [moment("2012-09-01","YYYY-MM-DD").toDate(), 1], ...
Flot does not automatically parse dates. If you want those to be used as-is then you should include the categories plugin. If you actually want to treat them as dates then you should convert them to dates as Nikos suggested and then take a look at the time plugin.

Categories