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

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
]);
}

Related

Sankey: Show dynamically text on x-axis

How to show dynamic text on x-axis based on transition. In my first case, I am getting two transitions(football -> basketball & basketball -> Gerard) so I will be showing two labels just like below
But When we get only one transition so how to handle label on the x-axis. What I need is when only one transition is there one label should only come. In the below case Semi-Final label should come.
Highcharts.chart('container', {
chart: {
showAxes: true
},
title: {
text: ''
},
xAxis: {
type: "category",
categories: ['Semi-Final','Final Phase'],
max: 2,
labels: {
x: 10,
y: 30,
},
lineColor: 'transparent',
tickLength: 0
},
yAxis: {
visible: false
},
series: [{
keys: ['from', 'to', 'weight'],
data: [
['Football', 'Cricket', 20 ],
],
type: 'sankey',
}]
});
The number of displayed labels depends on axis extremes. You can make max property dependent on the number of data:
events: {
load: function() {
var max = this.series[0].nodeColumns.length - 2;
this.xAxis[0].update({
max: max
})
}
}
Live demo: https://jsfiddle.net/BlackLabel/7s5h41qr/
API: https://api.highcharts.com/highcharts/xAxis.max

Chart to multiply data series without date data

I tried to customize a highstock chart for data series without date data.
series: [{ name: "nameA", data: [value1, value2, ... valueN]}, {...}]
Is there a way to build highstock chart like this without date data (only for value) with enabled rangeSelector.selected settings.
Also, I need to have buttons for different ranges with no date values.
If you use highstock.js source code and chart constructor, you will be able to create basic chart with highstock features:
Highcharts.chart('container', {
series: [{
data: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
}],
rangeSelector: {
enabled: true,
inputDateFormat: '%H:%M:%S.%L',
inputEditDateFormat: '%H:%M:%S.%L',
// Custom parser to parse the %H:%M:%S.%L format
inputDateParser: function(value) {
value = value.split(/[:\.]/);
return Date.UTC(
1970,
0,
1,
parseInt(value[0], 10),
parseInt(value[1], 10),
parseInt(value[2], 10),
parseInt(value[3], 10)
);
}
},
navigator: {
enabled: true
},
scrollbar: {
enabled: true
}
});
Live demo: http://jsfiddle.net/BlackLabel/h1yudspa/
answer on my question from comments is provided by ppotaczek:
navigator and rangeSelector based on time, so you have two options. You can use milliseconds as a basic numeric time value or create your own rangeSelecgor and change navigator axis type in Highcharts core: example
I chose a variant with ms, and set next options:
rangeSelector: {
buttons: [{
type: 'millisecond',
count: 10,
text: '10'
},{
type: 'millisecond',
count: 50,
text: '50'
},{
type: 'all',
text: 'All'
}]
},
...
navigator: {
xAxis: {
labels: {
formatter: function () {
return this.value;
}
}
}
},
...
xAxis: {
labels: {
format: '{value}'
},
},
...
series: [{data: [[0, value0], [1, value1]], ... [n, valueN]}]

Highstock bottom chart not shown

I'm using one the official highstock chart demo to create something similar with 2 charts stacked on top of each other. The problem is that the bottom chart (volume) is not displayed jsfiddle
A brief explanation of aapl-ohlc.json file will be helpful.
...
const data = JSON.parse(document.getElementById('ohlc-data').innerHTML);
// split the data set into ohlc and volume
const ohlc = data.map((a) => [a[0], a[1], a[2], a[3], a[4]])
const volume = data.map((a) => [a[0], a[5]])
// set the allowed units for data grouping
const groupingUnits = [
[
'week', // unit name
[1] // allowed multiples
],
[
'month', [1, 2, 3, 4, 6]
]
]
// create the chart
Highcharts.stockChart('container', {
legend: {
enabled: false
},
credits: {
enabled: false
},
exporting: {
enabled: false
},
scrollbar: {
enabled: false
},
rangeSelector: {
selected: 4,
inputEnabled: false
},
title: {
text: ''
},
yAxis: [{
labels: {
align: 'right',
x: -3
},
title: {
text: ''
},
height: '60%',
lineWidth: 2
}, {
labels: {
align: 'right',
x: -3
},
title: {
text: ''
},
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
}
}],
navigator: {
enabled: false
}
});
This line:
const volume = data.map((a) => [a[0], a[5]])
Points to an element that doesn't exist. a[5] is not defined (there are only five elements to each sub array, no sixth element), therefore you have no y values in your data, and therefore no data series to display.
I don't know what data element is supposed to represent volume, but for reference, just to show that it does work, here is an updated fiddle using
const volume = data.map((a) => [a[0], a[1]])
https://jsfiddle.net/jlbriggs/0t9rq1f7/1/
EDIT:
Note that in the demo example that you based your fiddle on, the file that they use is aapl-ohlcv.json, not aapl-ohlc.json, which does in fact have a 6th data element in each sub array.
https://www.highcharts.com/samples/data/jsonp.php?filename=aapl-ohlcv.json
https://github.com/highcharts/highcharts/blob/master/samples/data/aapl-ohlcv.json

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'],
...

Using JSON data with the jQuery highcharts plugin [closed]

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

Categories