javascript, Fron end Development - javascript

I'm trying to change the Highstock names. names = ['MSFT', 'AAPL', 'GOOG']; To names = ['ONE', 'TWO', 'THREE']; I want to change the names by any names. Please Help.
<script type="text/javascript">
var seriesOptions = [],
seriesCounter = 0,
names = ['ONE', 'TWO', 'THREE'];
/**
* Create the chart when all data is loaded
*/
function createChart() {
Highcharts.stockChart('container', {
rangeSelector: {
selected: 4
},
yAxis: {
labels: {
formatter: function () {
return (this.value > 0 ? ' + ' : '') + this.value + '%';
}
},
plotLines: [{
value: 0,
width: 2,
color: 'silver'
}]
},
plotOptions: {
series: {
compare: 'percent',
showInNavigator: true
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
valueDecimals: 2,
split: true
},
series: seriesOptions
});
}
$.each(names, function (i, name) {
$.getJSON('https://www.highcharts.com/samples/data/jsonp.php?filename=' + name.toLowerCase() + '-c.json&callback=?', function (data) {
seriesOptions[i] = {
name: name,
data: data
};
// As we're loading the data asynchronously, we don't know what order it will arrive. So
// we keep a counter and create the chart when all the data is loaded.
seriesCounter += 1;
if (seriesCounter === names.length) {
createChart();
}
});
});
</script>
But when i change these names Chart does not load. Any kind of Help Apreciated. How can i change these names please help. Thanks
Original Code.
<div id="container" style="height: 400px; min-width: 310px; margin-bottom:20px;"></div>
<script type="text/javascript">
var seriesOptions = [],
seriesCounter = 0,
names = ['MSFT', 'AAPL', 'GOOG'];
/**
* Create the chart when all data is loaded
*/
function createChart() {
Highcharts.stockChart('container', {
rangeSelector: {
selected: 4
},
yAxis: {
labels: {
formatter: function () {
return (this.value > 0 ? ' + ' : '') + this.value + '%';
}
},
plotLines: [{
value: 0,
width: 2,
color: 'silver'
}]
},
plotOptions: {
series: {
compare: 'percent',
showInNavigator: true
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
valueDecimals: 2,
split: true
},
series: seriesOptions
});
}
$.each(names, function (i, name) {
$.getJSON('https://www.highcharts.com/samples/data/jsonp.php?filename=' + name.toLowerCase() + '-c.json&callback=?', function (data) {
seriesOptions[i] = {
name: name,
data: data
};
// As we're loading the data asynchronously, we don't know what order it will arrive. So
// we keep a counter and create the chart when all the data is loaded.
seriesCounter += 1;
if (seriesCounter === names.length) {
createChart();
}
});
});
</script>

The chart is being populated with values from the line:
$.getJSON('https://www.highcharts.com/samples/data/jsonp.php?filename=' + name.toLowerCase() + '-c.json&callback=?', function (data) {
where name.tolowercase() takes the value of the names variable
names = ['MSFT', 'AAPL', 'GOOG'];
and fetches content from the file:
https://www.highcharts.com/samples/data/jsonp.php?filename=msft-c.json&callback=?
https://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?
https://www.highcharts.com/samples/data/jsonp.php?filename=goog-c.json&callback=?
So when you replace with
names = ['ONE', 'TWO', 'THREE'];
it does not find corresponding files on the server
https://www.highcharts.com/samples/data/jsonp.php?filename=one-c.json&callback=?
Hope it helps :).
The files will need to be placed on the server with relevant data for the charts to load.

You get an error when you want to get a JSON response for the files 'one', 'two' and 'three', for that reason the chart doesn't load.
To handle that exception I suggest you to use the jQuery's Ajax methods .fail() and .always() like this.
If you see my example, the chart loads, even without data.

Related

Highcharts / HighStock - How to parse JSON correctly

I’m trying to adapt this Highstock chart example for use with my data. Here it is their working in JSFiddle.
So I have multiple REST endpoints returning JSON in the following format (a collection of timestamps and decimals):
{
"data" : {
"1440151410002" : 0.00430013850798903,
"1440151420001" : 0.00403626002690655,
"1440151430002" : 0.00376276477784804,
"1440151440001" : 0.00381307106855453,
"1440151450002" : 0.0039385712356139,
"1440151460002" : 0.0038632842565838,
"1440151470002" : 0.00407696207243675,
"1440151480002" : 0.0042298508094211,
"1440151490002" : 0.00411973200243665,
"1440151500002" : 0.00360435516702981,
"1440151510001" : 0.00426992197206649,
"1440151520002" : 0.00354089360750537,
"1440151530002" : 0.00400806659263663
}
}
As in the HighStock example, the intention is to loop over the endpoints and pull in the JSON before creating the chart.
In order for HighStock to read it correctly, I realise I need to map it to something like:
[[timestamp, 1.23], [timestamp, 1.24] ...]
I'm having a problem figuring out how to map between my JSON format for each series and that required to render the chart correctly, so I'm currently getting a blank chart.
My JS looks like this:
$(function () {
var seriesOptions = [],
seriesCounter = 0,
names = ['P', 'Q', 'V', 'Q_C'],
// create the chart when all data is loaded
createChart = function () {
$('#chart4').highcharts('StockChart', {
rangeSelector: {
selected: 4
},
yAxis: {
labels: {
formatter: function () {
return (this.value > 0 ? ' + ' : '') + this.value + '%';
}
},
plotLines: [{
value: 0,
width: 2,
color: 'silver'
}]
},
plotOptions: {
series: {
compare: 'percent'
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
valueDecimals: 2
},
series: seriesOptions
});
};
$.each(names, function (i, name) {
$.getJSON('/live/data/' + name.toLowerCase(), function (data) {
seriesOptions[i] = {
name: name,
data: data['data']
};
// As we're loading the data asynchronously, we don't know what order it will arrive. So
// we keep a counter and create the chart when all the data is loaded.
seriesCounter += 1;
if (seriesCounter === names.length) {
createChart();
}
});
});
});
Any help would be appreciated!
Thanks,
Hugh.
You are passing a classic Object instead of an array in seriesOptions[i].data. You should do:
$.each(names, function (i, name) {
$.getJSON('/live/data/' + name.toLowerCase(), function (data) {
var data_tmp = [];
Object.keys(data["data"]).forEach(function (key) {
data_tmp.push([parseInt(key), data["data"][key]]);
});
seriesOptions[i] = {
name: name,
data: data_tmp
};
// As we're loading the data asynchronously, we don't know what order it will arrive. So
// we keep a counter and create the chart when all the data is loaded.
seriesCounter += 1;
if (seriesCounter === names.length) {
createChart();
}
});
});

HighStock graphic data array format

im using HighStock multiple series: http://www.highcharts.com/stock/demo/compare
The problem is that my application gives me this data format:
[data1],
[data2],
and HighStock is expecting this:
[
[data1],
[data2],
]
My JS for loading data is:
$(function () {
var seriesOptions = [],
seriesCounter = 0,
names = ['MSFT', 'AAPL', 'GOOG'],
// create the chart when all data is loaded
createChart = function () {
$('#graph1').highcharts('StockChart', {
legend: {
enabled: true,
align: 'center',
verticalAlign: 'bottom',
},
credits:{
enabled: false
},
title: {
text: 'Bitcoin Exchanges'
},
rangeSelector: {
selected: 4
},
yAxis: {
labels: {
formatter: function () {
return (this.value > 0 ? ' + ' : '') + this.value + '%';
}
},
plotLines: [{
value: 0,
width: 2,
color: 'silver'
}]
},
plotOptions: {
series: {
compare: 'percent'
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
valueDecimals: 2
},
series: seriesOptions
});
};
$.each(names, function (i, name) {
$.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=' + name.toLowerCase() + '-c.json&callback=?', function (data) {
seriesOptions[i] = {
name: name,
data: data
};
seriesCounter += 1;
if (seriesCounter === names.length) {
createChart();
}
});
});
});
How can I push that data to an parent array so the library can consume it?
Thanks in advance.

Drilldown on multiple Highcharts with the same data

Is it possible to have Highcharts drilldown on multiple graphs that are sharing the same data when one graph is clicked?
As an example, I included a JSFiddle that uses the demo code (browser percentages).
http://jsfiddle.net/Pq6gb/
var gridster;
$(function(){
gridster = $(".gridster ul").gridster({
widget_base_dimensions: [150, 150],
widget_margins: [5, 5],
helper: 'clone',
resize: {
enabled: true,
stop: function(e, ui, $widget) {
for (var i = 0; i < Highcharts.charts.length; i++) {
Highcharts.charts[i].reflow();
}
}
}
}).data('gridster');
});
$(function () {
Highcharts.data({
csv: document.getElementById('tsv').innerHTML,
itemDelimiter: '\t',
parsed: function (columns) {
var brands = {},
brandsData = [],
versions = {},
drilldownSeries = [];
// Parse percentage strings
columns[1] = $.map(columns[1], function (value) {
if (value.indexOf('%') === value.length - 1) {
value = parseFloat(value);
}
return value;
});
$.each(columns[0], function (i, name) {
var brand,
version;
if (i > 0) {
// Remove special edition notes
name = name.split(' -')[0];
// Split into brand and version
version = name.match(/([0-9]+[\.0-9x]*)/);
if (version) {
version = version[0];
}
brand = name.replace(version, '');
// Create the main data
if (!brands[brand]) {
brands[brand] = columns[1][i];
} else {
brands[brand] += columns[1][i];
}
// Create the version data
if (version !== null) {
if (!versions[brand]) {
versions[brand] = [];
}
versions[brand].push(['v' + version, columns[1][i]]);
}
}
});
$.each(brands, function (name, y) {
brandsData.push({
name: name,
y: y,
drilldown: versions[name] ? name : null
});
});
$.each(versions, function (key, value) {
drilldownSeries.push({
name: key,
id: key,
data: value
});
});
// Create the chart
$('#container').highcharts({
chart: {
type: 'pie'
},
title: {
text: 'Browser market shares. November, 2013.'
},
subtitle: {
text: 'Click the slices to view versions. Source: netmarketshare.com.'
},
plotOptions: {
series: {
dataLabels: {
enabled: true,
format: '{point.name}: {point.y:.1f}%'
}
}
},
tooltip: {
headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y:.2f}%</b> of total<br/>'
},
series: [{
name: 'Brands',
colorByPoint: true,
data: brandsData
}],
drilldown: {
series: drilldownSeries
}
})
}
});
});
$(function () {
Highcharts.data({
csv: document.getElementById('tsv').innerHTML,
itemDelimiter: '\t',
parsed: function (columns) {
var brands = {},
brandsData = [],
versions = {},
drilldownSeries = [];
// Parse percentage strings
columns[1] = $.map(columns[1], function (value) {
if (value.indexOf('%') === value.length - 1) {
value = parseFloat(value);
}
return value;
});
$.each(columns[0], function (i, name) {
var brand,
version;
if (i > 0) {
// Remove special edition notes
name = name.split(' -')[0];
// Split into brand and version
version = name.match(/([0-9]+[\.0-9x]*)/);
if (version) {
version = version[0];
}
brand = name.replace(version, '');
// Create the main data
if (!brands[brand]) {
brands[brand] = columns[1][i];
} else {
brands[brand] += columns[1][i];
}
// Create the version data
if (version !== null) {
if (!versions[brand]) {
versions[brand] = [];
}
versions[brand].push(['v' + version, columns[1][i]]);
}
}
});
$.each(brands, function (name, y) {
brandsData.push({
name: name,
y: y,
drilldown: versions[name] ? name : null
});
});
$.each(versions, function (key, value) {
drilldownSeries.push({
name: key,
id: key,
data: value
});
});
// Create the chart
$('#container2').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Browser market shares. November, 2013'
},
subtitle: {
text: 'Click the columns to view versions. Source: netmarketshare.com.'
},
xAxis: {
type: 'category'
},
yAxis: {
title: {
text: 'Total percent market share'
}
},
legend: {
enabled: false
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
format: '{point.y:.1f}%'
}
}
},
tooltip: {
headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y:.2f}%</b> of total<br/>'
},
series: [{
name: 'Brands',
colorByPoint: true,
data: brandsData
}],
drilldown: {
series: drilldownSeries
}
})
}
});
});
There is a pie chart and a bar chart displaying the same data and can drilldown individually. I would like to click on any browser in the pie/bar chart and have both charts filter down to versions of that browser.
How would I go about doing this? Thanks.
Yes, it's possible. This is what you need to implement:
on drilldown event you can find respective point on a second chart and simple call 1point.doDrilldown()1
on drillup even in one chart, call on a second chart.drillUp()
Note: You need to be aware of infinite loop (for example drillUp() in one chart will call drillup event, which will drillUp() first chart again.. ) - just add some flag to call drillUp/doDrilldown only once per user click.

Highcharts visualize, style series

I'm using Highcharts.visualize to draw the graph from a table containing the data.
You can test my working code here: http://jsfiddle.net/S2XM8/1/
I have two questions:
I want to have a separate styling for my "Additional value". How do I go about it?
Can I add data for the X-axis via the javascript? For example if I need to fill in the gap between 2014-05-27 and 2014-05-25 in the table.
Highcharts.visualize = function (table, options, tableClass) {
// the categories
options.xAxis.categories = [];
$('tbody th', table).each( function () {
options.xAxis.categories.push(this.innerHTML);
});
// the data series
options.series = [];
$('tr', table).each( function (i) {
var tr = this;
$('.graph', tr).each( function (j) {
if (i === 0) { // get the name and init the series
options.series[j] = {
name: this.innerHTML,
data: []
};
} else { // add values
options.series[j].data.push(parseFloat(this.innerHTML));
console.log(this.innerHTML);
}
});
});
options.title = { text: 'Some graph' };
$('#' + tableClass + '-graph').highcharts(options);
};
var tableNumber = document.getElementById('rank-table'),
options = {
chart: {
zoomType: 'x'
},
xAxis: {
tickInterval: 30,
reversed: true,
labels: {
rotation: 45
},
type: 'datetime',
dateTimeLabelFormats: { // don't display the dummy year
month: '%e. %b',
year: '%b'
}
},
yAxis: {
title: {
text: 'Rank'
},
min: 1,
reversed: true
},
legend: {
layout: 'vertical',
align: 'middle',
verticalAlign: 'bottom',
borderWidth: 0
}
};
Highcharts.visualize(tableNumber, options, 'number');
Both things are possible, but require to modify visualize method, see: http://jsfiddle.net/S2XM8/4/
You can set series options in a chart and then merge with data:
series: [{
// nothing special
}, {
type: 'column' // set series type for example
}]
And merging:
options.series[j] = options.series[j] || {};
options.series[j].name = this.innerHTML,
options.series[j].data = [];
Check parsed value before passing as point value:
var value = parseFloat(this.innerHTML);
if(isNaN(value)) { //null value - produces NaN when parsing
options.series[j].data.push(10);
} else {
options.series[j].data.push(value); // push value to the series
}

how do you create highstock multi line chart in highcharts

I need to createa multi line highstock type of chart:
My test.json file looks like this:
[{"name":"serverA","data":[[1372737609,2.6075],[1372737906,2.6533],[1372738205,2.7834],[1372738526,3.6527],[1372738802,0.6352],[1372739093,0.6073]]},{"name":"serverB","data":[[1372737602,36.3042],[1372737929,16.1145],[1372738218,6.4503],[1372738503,23.8908],[1372738803,3.9025],[1372739079,10.8216],[1372739371,3.1338]]},{"name":"serverC","data":[[1372737600,3.9025],[1372737908,13.8542],[1372738184,10.9094],[1372738491,14.6655],[1372738777,80.7615],[1372739081,6.9777],[1372739383,10.0971]]}]
This is my script:
(function() {
var seriesOptions = [],
yAxisOptions = [],
colors = Highcharts.getOptions().colors;
$.getJSON('test.txt', function(data) {
alert(data);
seriesOptions: data
createChart();
});
// create the chart when all data is loaded
function createChart() {
$('#container').highcharts('StockChart', {
chart: {
},
rangeSelector: {
selected: 4
},
yAxis: {
labels: {
formatter: function() {
return (this.value > 0 ? '+' : '') + this.value + '%';
}
},
plotLines: [{
value: 0,
width: 2,
color: 'silver'
}]
},
plotOptions: {
series: {
compare: 'percent'
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
valueDecimals: 2
},
series: seriesOptions
});
}
});
I get this error:
Uncaught TypeError: undefined is not a function
any ideas what I am doing wrong here?
Change from: seriesOptions: data to seriesOptions = data;

Categories

Resources