Using JSON data with the jQuery highcharts plugin [closed] - javascript

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
<script type="text/javascript">
var chart;
$(document).ready(function() {
// Define the options
var options = {
chart: {
renderTo: 'container'
},
title: {
text: 'Daily visits at www.highcharts.com'
},
subtitle: {
text: 'Source: Google Analytics'
},
xAxis: {
type: 'datetime',
tickInterval: 7 * 24 * 3600 * 1000, // One week
tickWidth: 0,
gridLineWidth: 1,
labels: {
align: 'left',
x: 3,
y: -3
}
},
yAxis: [{ // Left Y axis
title: {
text: null
},
labels: {
align: 'left',
x: 3,
y: 16,
formatter: function() {
return Highcharts.numberFormat(this.value, 0);
}
},
showFirstLabel: false
}, { // right y axis
linkedTo: 0,
gridLineWidth: 0,
opposite: true,
title: {
text: null
},
labels: {
align: 'right',
x: -3,
y: 16,
formatter: function() {
return Highcharts.numberFormat(this.value, 0);
}
},
showFirstLabel: false
}],
legend: {
align: 'left',
verticalAlign: 'top',
y: 20,
floating: true,
borderWidth: 0
},
tooltip: {
shared: true,
crosshairs: true
},
plotOptions: {
series: {
cursor: 'pointer',
point: {
events: {
click: function() {
hs.htmlExpand(null, {
pageOrigin: {
x: this.pageX,
y: this.pageY
},
headingText: this.series.name,
maincontentText: Highcharts.dateFormat('%A, %b %e, %Y', this.x) +':<br/> '+
this.y +' visits',
width: 200
});
}
}
},
marker: {
lineWidth: 1
}
}
},
series: [{
name: 'All visits',
lineWidth: 4,
marker: {
radius: 4
}
}, {
name: 'New visitors'
}]
}
// Load data asynchronously using jQuery. On success, add the data
// to the options and initiate the chart.
// This data is obtained by exporting a GA custom report to TSV.
// http://api.jquery.com/jQuery.get/
jQuery.get('analytics.tsv', null, function(tsv) {
var lines = [],
listen = false,
date,
// Set up the two data series.
allVisits = [],
newVisitors = [];
try {
// Split the data return into lines and parse them.
tsv = tsv.split(/\n/g);
jQuery.each(tsv, function(i, line) {
// Listen for data lines between the Graph and Table headers.
if (tsv[i - 3] == '# Graph') {
listen = true;
} else if (line == '' || line.charAt(0) == '#') {
listen = false;
}
// All data lines start with a double quote.
if (listen) {
line = line.split(/\t/);
date = Date.parse(line[0] +' UTC');
allVisits.push([
date,
parseInt(line[1].replace(',', ''), 10)
]);
newVisitors.push([
date,
parseInt(line[2].replace(',', ''), 10)
]);
}
});
} catch (e) { alert(e.message) }
options.series[0].data = allVisits;
options.series[1].data = newVisitors;
chart = new Highcharts.Chart(options);
});
});
</script>
Above is example code for a jQuery plugin, 'highcharts'. I am trying to get the data from a JSON file if the JSON string is as: { name: 'allVisits', data: [1, 0, 4] }, { name: 'newVisits', data: [5, 7, 3] }.
The example file is getting the data from a 'tsv' file, so I am trying to get the data from the JSON file instead.

From your short JSON example, I would say it's invalid.
{ name: 'allVisits', data: [1, 0, 4] }, { name: 'newVisits', data: [5, 7, 3] }
Should be:
[{"name":"allVisits", "data": [1, 0, 4] }, {"name": "newVisits", "data": [5, 7, 3] }]
If I recall correctly, jQuery does some JSON validation.
Once your file is valid JSON, you can use jQuery.getJSON instead of jQuery.get.
jQuery.getJSON( 'file.json' , function( data ){
alert( data[0].name );
// do your thang with data
});
Test your JSON with JSONLint

Related

highchart with a specific json format in django

I received data from an api in this format:
[{"t":"2010-05-06T00:00:00Z","v":294},
{"t":"2010-05-07T00:00:00Z","v":103},
{"t":"2010-05-08T00:00:00Z","v":293},
{"t":"2010-05-09T00:00:00Z","v":113}]
how can I draw a chart with highchart in my website with them. "t" have to convert to "time" and "v" to "volume"
this is my JS file. I need to remain in the chart property as much as I can.
Highcharts.chart('container', {
chart: {
scrollablePlotArea: {
minWidth: 700
}
},
data: {
},
xAxis: {
tickInterval: 7 * 24 * 3600 * 1000, // one week
tickWidth: 0,
gridLineWidth: 1,
labels: {
align: 'left',
x: 3,
y: -3
}
},
yAxis: [{ // left y axis
title: {
text: null
},
legend: {
align: 'left',
verticalAlign: 'top',
borderWidth: 0
},
tooltip: {
shared: true,
crosshairs: true
},
plotOptions: {
series: {
cursor: 'pointer',
className: 'popup-on-click',
marker: {
lineWidth: 1
}
}
},
});
You need to map your data to the format required by Highcharts.
const data = [{
"t": "2010-05-06T00:00:00Z",
"v": 294
},
...
];
const seriesData = data.map(dataEl => [new Date(dataEl.t).getTime(), dataEl.v]);
Highcharts.chart('container', {
...,
series: [{
data: seriesData
}]
});
Live demo: http://jsfiddle.net/BlackLabel/z74pyfbj/
API Reference: https://api.highcharts.com/highcharts/series.column.data

Highcharts JSON formatting - splitting up and preprocessing data for charts?

I'm trying to get data from this JSON: https://min-api.cryptocompare.com/data/histominute?fsym=BTC&tsym=USD&limit=60&aggregate=3&e=CCCAGG
into hightcharts.
I have this chart that is working properly, but I can't get proper formatting for JSON above: still learning javascript. And I like to learn on project, piece by piece, with some cause at least :)
Also, this timestamp is bugging me...
$.getJSON('https://www.highcharts.com/samples/data/jsonp.php?filename=aapl-ohlcv.json&callback=?', function (data) {
var ohlc = [],
volume = [],
dataLength = data.length,
groupingUnits = [[
'week',
[1]
], [
'month',
[1, 2, 3, 4, 6]
]],
i = 0;
for (i; i < dataLength; i += 1) {
ohlc.push([
data[i][0], // the date
data[i][1], // open
data[i][2], // high
data[i][3], // low
data[i][4] // close
]);
volume.push([
data[i][0], // the date
data[i][5] // the volume
]);
}
// create the chart
Highcharts.stockChart('container', {
rangeSelector: {
selected: 1
},
title: {
text: 'AAPL Historical'
},
yAxis: [{
labels: {
align: 'right',
x: -3
},
title: {
text: 'OHLC'
},
height: '60%',
lineWidth: 2,
resize: {
enabled: true
}
}, {
labels: {
align: 'right',
x: -3
},
title: {
text: 'Volume'
},
top: '65%',
height: '35%',
offset: 0,
lineWidth: 2
}],
tooltip: {
split: true
},
series: [{
type: 'candlestick',
name: 'AAPL',
data: ohlc,
dataGrouping: {
units: groupingUnits
}
}, {
type: 'column',
name: 'Volume',
data: volume,
yAxis: 1,
dataGrouping: {
units: groupingUnits
}
}]
});
});
Could someone help out? How to separate properly info from that JSON and format it so that highcharts can visualize it?
Thanks in advance for any help!
Refer to this live demo: http://jsfiddle.net/kkulig/8qk0mjzp/
Data property from object fetched via getJSON() contains the data to be plotted on the chart.
Every point has JSON format (not an array as in the code that you posted) so its properties need to be referred like this:
for (i; i < dataLength; i += 1) {
ohlc.push([
data[i].time * 1000, // the date
data[i].open, // open
data[i].high, // high
data[i].low, // low
data[i].close // close
]);
volume.push([
data[i].time * 1000, // the date
data[i].volumefrom, // low
data[i].volumeto // high
]);
}

Pass 3 values in highcharts series

I have a scatter chart from Highcharts, in the y axis i put 'Intensity' values,and in the x axis i have datetimes (month,day,year).
chart: {
type: 'scatter',
zoomType: 'xy',
renderTo: 'chartContainer'
},
rangeSelector: {
enabled: true
},
xAxis: {
title: {
enabled: true
},
type: 'datetime',
dateTimeLabelFormats:{
month: '%e. %b %Y',
year: '%b'
},
startOnTick: true,
endOnTick: true,
showLastLabel: true
},
yAxis: {
title: {
text: 'Intensity'
},
min: 0,
max: 100
},
plotOptions: {
scatter: {
marker: {
radius: 5,
states: {
hover: {
enabled: true,
lineColor: 'rgb(100,100,100)'
}
}
},
states: {
hover: {
marker: {
enabled: false
}
}
},
events: {
click: function(event) {
showMoreData();
}
}
}
},
series: [{
name: 'Male',
color: 'rgba(144,36,58, .8)',
data: getDataParsed()
}]
These data are loaded from another function getDataParsed(), where I do a ajax GET and get multiple data . The question is how i pass more data (also Intensity and Datetimes) so i can used later in the scatter chart.
function getDataParsed() {
var serie = [];
var i=0;
dolorCollect.forEach(function (dato) {
var arr = dato.FECHA_INICIO.split("/");
var hour = dato.HORA_INICIO.split(":");
serie[i]= [Date.UTC(arr[2],arr[1]-1,arr[0],hour[0],hour[1]),dato.INTENSIDAD_DOLOR];
i++;
});
return serie;
}
To have more data in each data point in series' data you can:
do as Rahul Sharma suggested in his comment - set data point as object with named properties. More info in API - see 3rd way of data format:
An array of objects with named values. The objects are point configuration objects as seen below. If the total number of data points exceeds the series' turboThreshold, this option is not available.
data: [{
x: 1,
y: 2,
name: "Point2",
color: "#00FF00"
}, {
x: 1,
y: 4,
name: "Point1",
color: "#FF00FF"
}]
or set data as array of arrays - as you do now, but with more data in point array. To allow Highcharts proper way to decode your new format set keys.
So same data can be set using code like:
series:[{
data: [
[1, 2, "Point2", "#00FF00"],
[1, 4, "Point1", "#FF00FF"]
],
keys: ['x','y','name','color'],
...

ng-style not working in div which is rendering Highchart

I am trying to dynamically change the height of the chart depending upon the number of horizontal bars displayed in the chart.
I am using ng-style to pass css dynamically. ng-style works fine (http://jsfiddle.net/7veB2/) if I am not rendering the chart.
The link (http://jsfiddle.net/gsthilak/atwyh073/) has a working highcharts bar chart in horizontal fashion.
I am trying to render the chart in id="container" in the JSFiddle link below, but it does not render the chart.
JSFiddle (not working) link: http://jsfiddle.net/gsthilak/7veB2/19/
I am trying to change the height of the chart dynamically because the chart looks cramped if there are too many bars within small space.
JS Code looks like:
var app = angular.module('myApp', []);
function ctrl($scope){
$scope.myStyle= {
"width":"900px",
"background":"red"
}
$scope.chartHeight = 400+"px"
$scope.chartStyle = {
"height":$scope.chartHeight,
"margin":"0 auto",
"min-width":"310px",
"max-width":"624px"
}
}
var baseValue = 0;
var shadowBaseValue = 0;
var outputTitle = "Net Sales";
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container'
},
credits: {},
exporting: {},
legend: {},
title: {
text: outputTitle
},
subtitle: {
text: "MM $"
},
plotOptions: {
series: {
dataLabels: {
enabled: true,
formatter: function () {
var index = this.series.chart.xAxis[0].categories.indexOf(this.x);
if (this.series.userOptions.labels === undefined) {
return this.y + baseValue;
}
return this.key === "Combined Uncertainty" || this.key === "" ? "" : this.series.userOptions.labels[index];
}
}
}
},
xAxis: {
title: {
text: 'Factor'
},
allowDecimals: false,
categories: ['Annual Revenue', 'Number of Years', 'Annual Costs', 'Combined Uncertainty', '']
},
yAxis: [{
title: {
text: 'MM $'
},
labels: {
formatter: function () {
return this.value + baseValue;
}
}
}],
series: [{
threshold: 29.5,
name: 'Low',
grouping: false,
type: 'bar',
data: [{
x: 0,
y: 12.15 - baseValue,
}, {
x: 1,
y: 15.45 - baseValue,
}, {
x: 2,
y: 31.25 - baseValue,
}, {
x: 3,
y: 12.15 - baseValue,
}],
labels: [10, 5, 1, 2]
}, {
threshold: 29.5,
name: 'High',
grouping: false,
type: 'bar',
data: [{
x: 0,
y: 46.86 - baseValue,
}, {
x: 1,
y: 42.28 - baseValue,
}, {
x: 2,
y: 27.77 - baseValue,
}, {
x: 3,
y: 46.86 - baseValue,
}],
labels: [30, 10, 3, 4]
}]
});
HTML code looks like:
<div ng-app="myApp" ng-controller="ctrl">
<div id="container" ng-style="chartStyle"></div>
<div style="width: 250px; overflow: scroll; " >
<div ng-style="myStyle">Hello!</div>
</div>
</div>
Please help me to solve this problem. Thanks!

Trying to converted array of data to work with Highcahrts Ajax loaded data example

I am building a dashboard in Ruby on Rails that creates charts/graphs for analysis out of google analytics data using HighchartsJS. I am following this example from Highcharts for Ajax Data implementation. The csv data they are using to create the line graph is here.
Currently I am retrieving google analytics data using Core Client API V3 and gives me a result back the form of
[[Year, Month, Day, Session Hits, Unique Hits], [Year, Month, Day, Session Hits, Unique Hits], [Year, Month, Day, Session Hits, Unique Hits], ...]
An example
[["2014", "11", "24", "21","2"], [2014", "11", "25", "8", "0"],["2014", "11", "26", "11", "3"], [2014", "11", "27", "5", "1"]]
I want to convert this data into a form just like the csv data Highcharts is using as I want a graph that looks exactly like this example.
I tried converting it as such
def web_traffic_results
#Instantiate array of datapoints to be returned for campaign traffic chart
wt_datapoints = "Day,Visits,Unique Visitors"
#for each element in ga queried results parse the data into highcharts example format
traffic_query.each do |rowContent|
row_year = rowContent[0]
row_month = rowContent[1]
row_day = rowContent[2]
row_date = "#{row_day}/#{row_month}/#{row_year}"
total_hits = rowContent[3]
new_hits = rowContent[4]
wt_datapoints = wt_datapoints + "\n#{row_date},#{total_hits},#{new_hits}"
end
return [wt_datapoints]
end
In the reference in which I am rendering the data, [wt_datapoints] renders like this
["Day,Visits,Unique Visitors\n11/04/2014,2,0\n11/13/2014,1,0\n11/20/2014,2,0\n11/21/2014,1,0\n11/24/2014,21,0\n11/25/2014,8,0"]
Here is where I call the chart render and pipe the data
<script>
$(document).ready(function() {
WebTrafficChart.render('/mgt/web/<%= #id %>/graphs/traffic', '#web_traffic_chart');
});
</script>
This calls the below which is mostly taken from the example linked on the top except for the data
window.WebCampaignTrafficChart = {
render: function(data, selector) {
// Get the CSV and create the chart
$.getJSON(data, function (csv) {
// transform
// {data: []}
$('#web_traffic_chart').highcharts({
data: {
csv: csv
},
title: {
text: 'Total Traffic'
},
subtitle: {
text: 'Source: Google Analytics'
},
xAxis: {
tickInterval: 7 * 24 * 3600 * 1000, // one week
tickWidth: 0,
gridLineWidth: 1,
labels: {
align: 'left',
x: 3,
y: -3
}
},
yAxis: [{ // left y axis
title: {
text: null
},
labels: {
align: 'left',
x: 3,
y: 16,
format: '{value:.,0f}'
},
showFirstLabel: false
}, { // right y axis
linkedTo: 0,
gridLineWidth: 0,
opposite: true,
title: {
text: null
},
labels: {
align: 'right',
x: -3,
y: 16,
format: '{value:.,0f}'
},
showFirstLabel: false
}],
legend: {
align: 'left',
verticalAlign: 'top',
y: 20,
floating: true,
borderWidth: 0
},
tooltip: {
shared: true,
crosshairs: true
},
plotOptions: {
series: {
cursor: 'pointer',
point: {
events: {
click: function (e) {
hs.htmlExpand(null, {
pageOrigin: {
x: e.pageX || e.clientX,
y: e.pageY || e.clientY
},
headingText: this.series.name,
maincontentText: Highcharts.dateFormat('%A, %b %e, %Y', this.x) + ':<br/> ' +
this.y + ' visits',
width: 200
});
}
}
},
marker: {
lineWidth: 1
}
}
},
series: [{
name: 'All visits',
lineWidth: 4,
marker: {
radius: 4
}
}, {
name: 'New visitors'
}]
});
});
}
}
This implementation does not work and I was wondering if I could get some help and feedback regarding this question. Thanks in advance.

Categories