Issue to add dynamic value in Highcharts jquery - javascript

I am facing an issue to add the dynamic value in Highcharts Jquery. I have two arrays like name and value
name/categoryname - ["ZYG", "BLA", "GAS", "LBE", "LIM", "EMB", "NAU"]
value/basevalue - [483.7932253,601.125844,680.2910403,886.7269613,548.3400347,630.8979143,0]
face the issue in passing the base value in. I tried to pass the value in the array and string type. The issue is not solved yet.
I used the bar chart to display. The coding is here. Normally coding works fine. The issue faced when I use dynamic value.
function displaychart(obj)
{
var categoryname = [];
$.each(obj['name'], function( key, value ) {
categoryname.push(value);
});
var ybasevalue = "[";
$.each(obj['basevalue'], function( key, value ) {
ybasevalue += value + ",";
});
ybasevalue += "]";
Highcharts.chart('container'+i, {
chart: {
type: 'bar'
},
title: {
text: 'Protein Sequence'
},
subtitle: {
text: 'Source'
},
xAxis: {
categories: categoryname,
title: {
text: null
}
},
yAxis: {
min: 0,
title: {
text: 'Proteomics',
align: 'high'
},
labels: {
overflow: 'justify'
}
},
tooltip: {
valueSuffix: ''
},
plotOptions: {
bar: {
dataLabels: {
enabled: true
}
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: 0,
y: 180,
floating: true,
borderWidth: 1,
backgroundColor: ((Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'),
shadow: true
},
credits: {
enabled: false
},
series:[
{
name: 'Protein',
data: ybasevalue
},
]
});
}
}

I pass an array of Strings instead of an array of Numbers. Values inside single or double quotes are Strings in JavaScript.
So I use
var ybasevalue = [];
$.each(obj[i]['basevalue'], function( key, value ) {
ybasevalue.push(parseInt(value)); });

Related

incorrect callback function string

I am using this code belong to plot currency change values but there is a problem while plotting chart.
$(document).ready(function () {
localhost1 = {}; //our global namespace variable
localhost1.chg_percent = [];
localhost1.currency =[];
localhost1.chart1 = {yAxisMin : null, yAxisMax : null }; //this object holds things belonging to this chart1
var url1 = 'http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json&view=basic';
$.ajax({
url: url1,
cache: false,
dataType: 'jsonp',
context: localhost1,
success: function(data) {
for(var i=0; i<data.list.resources.length; i++) {
this.currencyObj = data.list.resources[i].fields;
this.chg_percent.push(parseFloat(data.list.resources[i].resource.fields.chg_percent));
this.currency.push(data.list.resources[i].resource.fields.name);
}
this.chart1.yAxisMax = (function(array){
var number_array = [];
for(var i=0; i<array; i++){
if(array[i] != null){
number_array.push(array[i]);
}
}
return math.max.apply(Math, number_array);
})(this.chg_percent);
this.chart1.yAxisMin = (function(array){
var number_array = [];
for(var i=0; i<array; i++){
if(array[i] != null){
number_array.push(array[i]);
}
}
return math.min.apply(Math, number_array);
})(this.chg_percent);
this.chart1.data.series[0].data = this.chg_percent;
this.chart1.data.xAxis.categories = this.currency;
chart = new Highcharts.Chart(this.chart1.data);
console.log(data);
}
});
localhost1.chart1.data = {
chart: {
renderTo: 'container',
type: 'bar'
},
title: {
text: 'Historic World Population by Region'
},
subtitle: {
text: 'Source: Source : yahoo'
},
xAxis: {
categories: null,
title: {
text: null
}
},
yAxis: {
min: localhost1.chart1.yAxisMin,
max: localhost1.chart1.yAxisMax,
title: {
text: 'Daily Percentage Change',
align: 'high'
},
labels: {
overflow: 'justify'
}
},
tooltip: {
formatter: function(){
return ''+
this.series.name +': '+ this.y +' %';
}
},
plotOptions: {
bar: {
dataLabels: {
enabled: true
}
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -1,
y: 1,
floating: true,
borderWidth: 1,
backgroundColor: '#FFFFFF',
shadow: true
},
credits: {
enabled: false
},
series: [{
name: 'Daily Change',
data: null
}]
};
});
when i run this code, i get an error message in console "Not acceptable : http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json&view=basic&callback=jQuery18203581249208157574_1452451202663&_=1452451202773".
though the api i have used is correct but the string that callback function returns seems to be incorrect.

High Charts windrose from API data (JSON)

I'm quite new here (and to web development in general), so please forgive any misuses that I perpetuate... I'm trying to create a basic windrose plot with data returned (in JSON) from the MesoWest Mesonet API service. I'm using HighCharts (or attempting to), and cannot quite get it to work. Perhaps this is due to my methodology of obtaining the data from the API itself as I'm a complete amateur in this regard. The following is the Javascript code, followed by the HTML for the page. Could someone please take a look and let me know what I've done wrong? Nothing displays on the page when I attempt to load it. In addition, if you're curious as to the specifics of an API call for MesoWest, like the one I've employed here, please see http://mesowest.org/api/docs/
The .js script:
var windrose = {
divname: "windrosediv",
tkn: "eecfc0259e2946a68f41080021724419",
load:function()
{
console.log('loading')
if (!window.jQuery) {
var script = document.createElement("script");
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
script.type = 'text/javascript';
document.getElementByTagName("head")[0].appendChild(script);
setTimeout(pollJQuery, 100)
return
}
this.div = $("#"+this.divname);
this.request('WBB');
},
pollJQuery:function()
{
if (!window.jQuery) {
setTimeout(pollJQuery,100);
} else {
load();
}
},
request:function(stn){
console.log("making a request")
$.getJSON(http://api.mesowest.net/v2/stations/nearesttime?callback=?',
{
stid:stn,
within:1440,
units:'english',
token:windrose.tkn
}, this.receive);
},
receive:function (data)
{
console.log(data,windrose);
stn = data.STATION[0]
dat = stn.OBSERVATIONS
spd += Math.round(dat.wind_speed_value_1.value)
dir += dat.wind_direction_value_1.value
windDataJSON = [];
for (i = 0; i < dir.length; i++) {
windDataJSON.push([ dir[i], spd[i]
]);
},
}
$(function () {
var categories = ['0', '45', '90', '135', '180', '225', '270', '315'];
$('#container').highcharts({
series: [{
data: windDataJSON
}],
chart: {
polar: true,
type: 'column'
},
title: {
text: 'Wind Rose'
},
pane: {
size: '85%'
},
legend: {
align: 'right',
verticalAlign: 'top',
y: 100,
layout: 'vertical'
},
xAxis: {
min: 0,
max: 360,
type: "",
tickInterval: 22.5,
tickmarkPlacement: 'on',
labels: {
formatter: function () {
return categories[this.value / 22.5] + '°';
}
}
},
yAxis: {
min: 0,
endOnTick: false,
showLastLabel: true,
title: {
text: 'Frequency (%)'
},
labels: {
formatter: function () {
return this.value + '%';
}
},
reversedStacks: false
},
tooltip: {
valueSuffix: '%'
},
plotOptions: {
series: {
stacking: 'normal',
shadow: false,
groupPadding: 0,
pointPlacement: 'on'
}
}
});
});
And the HTML:
<!DOCTYPE html>
<html>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/highcharts-more.js"></script>
<script src="https://code.highcharts.com/modules/data.js">`enter code </script>
<script src="https://code.highcharts.com/modules/exporting.js"> </script>
<div id="container" style="min-width: 420px; max-width: 600px; height: 400px; margin: 0 auto"></div>
<p class="ex">
<script type="text/javascript" src="http://home.chpc.utah.edu/~u0675379/apiDemos/windTest.js"></script>
</p>
</html>
I appreciate any guidance in this regard, thanks!!!
-Will
#W.Howard, I think the problem here is how you are treating and preparing the JSON response from the API. Consider the following JavaScript to retrieve and parse out the data:
/*
* Helper function
* scalarMultiply(array, scalar)
*/
function scalarMultiply(arr, scalar) {
for (var i = 0; i < arr.length; i++) {
arr[i] = arr[i] * scalar;
}
return arr;
}
/*
* getQuery(station, api_token)
*/
function getQuery(station, mins, api_token) {
$.getJSON('http://api.mesowest.net/v2/stations/timeseries?callback=?', {
/* Specify the request parameters here */
stid: station,
recent: mins, /* How many mins you want */
obtimezone: "local",
vars: "wind_speed,wind_direction,wind_gust",
jsonformat: 2, /* for diagnostics */
token: api_token
},
function(data) {
try {
windSpeed = data.STATION[0].OBSERVATIONS.wind_speed_set_1;
windDir = data.STATION[0].OBSERVATIONS.wind_direction_set_1;
windGust = data.STATION[0].OBSERVATIONS.wind_gust_set_1;
} catch (err) {
console.log("Data is invalid. Check your API query");
console.log(this.url);
exit();
}
/* Convert from knots to mph */
windSpeed = scalarMultiply(windSpeed, 1.15078);
//windGust = scalarMultiply(windGust, 1.15078);
/* Create and populate array for plotting */
windData = [];
for (i = 0; i < windSpeed.length; i++) {
windData.push([windDir[i], windSpeed[i]]);
}
/* Debug */
// console.log(windData);
console.log(this.url);
plotWindRose(windData, mins);
})
};
What we had now is an 2D array with wind direction and wind speed that we can pass to the plotting function. Below is the updated plotting function:
/*
* Plot the wind rose
* plotWindRose([direction, speed])
*/
function plotWindRose(windData, mins) {
/*
* Note:
* Because of the nature of the data we will accept the HighCharts Error #15.
* --> Highcharts Error #15 (Highcharts expects data to be sorted).
* This only results in a performance issue.
*/
var categories = ["0", "45", "90", "135", "180", "225", "270", "315"];
$('#wind-rose').highcharts({
series: [{
name: "Wind Speed",
color: '#cc3000',
data: windData
}],
chart: {
type: 'column',
polar: true
},
title: {
text: 'Wind Direction vs. Frequency (Last ' + mins/60. + ' hours)'
},
pane: {
size: '90%',
},
legend: {
align: 'right',
verticalAlign: 'top',
y: 100,
text: "Wind Direction"
},
xAxis: {
min: 0,
max: 360,
type: "",
tickInterval: 45,
tickmarkPlacement: 'on',
labels: {
formatter: function() {
return categories[this.value / 45] + '\u00B0';
}
}
},
yAxis: {
min: 0,
endOnTick: false,
showLastLabel: true,
title: {
text: 'Frequency (%)'
},
labels: {
formatter: function() {
return this.value + '%';
}
},
reversedStacks: false
},
tooltip: {
valueSuffix: '%'
},
plotOptions: {
series: {
stacking: 'normal',
shadow: false,
groupPadding: 20,
pointPlacement: 'on'
}
}
});
}
You can see it all here at https://gist.github.com/adamabernathy/eda63f14d79090ab1ea411a8df1e246e . Best of luck!

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.

Add start-date and end-date as a Xaxis label in highchart

I use date as a string in my chart.
How can I use my start-date and end-date string variables as a label in my xAxis?
start-date = '10.02.2013'
end-date = '10.05.2013'
The code and the chart image is attached. The only thing I need to do is to add startDateLabel and endDateLabel.
var dateEndLabel, dateStartLabel, i, j, lastDate, seriesData, x, y;
i = 0;
seriesData = new Array();
lastDate = data[i].Values.length - 1;
dateStartLabel = data[i].Values[0].Time;
dateEndLabel = data[i].Values[lastDate].Time;
while (i < data.length) {
seriesData[i] = [];
j = 0;
x = [];
y = [];
while (j < data[i].Values.length) {
x = data[i].Values[j].Time;
y = data[i].Values[j].Value;
seriesData[i].push([x, y]);
j++;
}
i++;
}
return $("#criticalWPtrend").highcharts({
chart: {
type: "line"
},
area: {
height: "100%",
width: "100%",
margin: {
top: 20,
right: 30,
bottom: 30,
left: 50
}
},
title: {
text: ""
},
subtitle: {
text: ""
},
legend: {
layout: "vertical",
verticalAlign: "right",
align: "right",
borderWidth: 0
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
day: '%m-%d'
},
tickInterval: 24 * 3600 * 1000
},
yAxis: {
title: {
text: 'Value'
},
lineWidth: 1,
min: 0,
minorGridLineWidth: 0,
gridLineWidth: 0,
alternateGridColor: null
},
tooltip: {
valueSuffix: " "
},
plotOptions: {
series: {
marker: {
enabled: false
},
stickyTracking: {
enabled: false
}
},
line: {
lineWidth: 2,
states: {
hover: {
lineWidth: 3
}
},
marker: {
enabled: false
}
}
},
series: [
{
name: data[0].Name,
data: seriesData[0]
}, {
name: data[1].Name,
data: seriesData[1]
}, {
name: data[2].Name,
data: seriesData[2]
}, {
name: data[3].Name,
data: seriesData[3]
}, {
name: data[4].Name,
data: seriesData[4]
}, {
name: data[5].Name,
data: seriesData[5]
}
],
navigation: {
menuItemStyle: {
fontSize: "10px"
}
}
});
});
Yes, this is possible with the renderer method. See this basic example.
chart.renderer.text('10.02.2013', 0, 300)
.attr({
rotation: 0
})
.css({
color: '#4572A7',
fontSize: '16px'
})
.add();
You are going to need to pay attention to the x/y locations (the 2 other params) to place it correctly. You can also modify the text styling.
I'm not sure, but i think you just need to update your xAxis by update method
this.xAxis[0].update({
title: {
text: "start-date = '10.02.2013' end-date = '10.05.2013'",
style: {
fontSize: '10px'
}
}
});
Here's example: http://jsfiddle.net/FEwKX/
But!
If your mean that the start and end dates need to tie to edges, you must specify xAxis settings in config
xAxis: {
categories: categoriesArray
}
where categoriesArray is array like this:
['10.02.2013', '', '', '', '', '', '', '', '', '', '', '10.05.2013']
It should be the same lenght as your lenght of series data.
Check out here: http://jsfiddle.net/FEwKX/1/
Hope that'll help you.
You can also use labelFormatter and http://api.highcharts.com/highcharts#xAxis.labels.formatter and check if labels isFirst or isLast then use your dates, in other cases return proper value (like number).

Highcharts + Highslide: When opening a new highslide popup or clicking anywhere else, close any previously opened popups

So, I discovered that when you have are utilizing highslides in conjuction with highcharts data, its possible to keep clicking new datapoints and have an endless number of modal windows pop up. I wanted to build something that will close an existing highslide popup window if you open a new highslide or if you click anywhere else, either on the screen or on a filter.
I wrote this little function and added it to my beginning statement but it did not work.
<body onclick="javascript:parent.window.hs.close();">
And here is my full example:
The question is, can someone show me an example where I can accomplish my above described behavior?
$(function () {
$('#container').highcharts({
chart: {
type: 'scatter',
zoomType: 'xy'
},
title: {
text: 'Q1 Eanings and Outlook Forecast',
x: -100
},
subtitle: {
text: 'professional',
x:-100
},
xAxis: {
title: {
enabled: false,
text: 'Future Outlook'
},
labels:{formatter: function() {} },
startOnTick: true,
endOnTick: true,
showLastLabel: true
},
yAxis: {
title: {
enabled:false,
text: 'Current Quarter'
},
labels: {
formatter: function() {
//return this.value + ' ';
}
},
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
// x: 100,
y: 70,
floating: false,
backgroundColor: '#FFFFFF',
borderWidth: 1
},
load: function() {
var legend = $('#container .highcharts-legend');
var x = legend.position().left;
var y = legend.position().top - (this.chartHeight - this.plotTop - this.plotHeight - this.options.chart.spacingBottom);
legend.attr({
transform: 'translate(' + x + ',' + y + ')'
});
},
plotOptions: {
scatter: {
marker: {
radius: 5,
states: {
hover: {
enabled: true,
lineColor: 'rgb(100,100,100)'
}
}
},
states: {
hover: {
marker: {
enabled: true
}
}
},
tooltip: {
headerFormat: '<b>{series.name}:</b><br>',
pointFormat: '{point.hover}<br><br><b>Current Q: </b>{point.y}/100<br><b>Outlook: </b>{point.x}/100<br><br><div style="text-align:center;">(click for more detail)</div>'
},
cursor: 'pointer',
point: {
events: {
click: function(event) {
hs.htmlExpand(null, {
pageOrigin: {
x: this.pageX,
y: this.pageY
},
headingText: this.ticker,
maincontentText: '<b>Detail:</b> ' + this.info,
width: 250
});
hs.Expander.prototype.onBeforeClose = function(sender) {
}
},
}
},
events: {
legendItemClick: function(event) {
if (!this.visible)
return true;
var seriesIndex = this.index;
var series = this.chart.series;
for (var i = 0; i < series.length; i++)
{
if (series[i].index != seriesIndex)
{
series[i].visible ? series[i].hide() : series[i].show();
}
}
return false;
}
},
}
},
series: [{
name: 'Weak Outlook (24)',color: 'red',data: [
{x: 40,y:10,ticker:'Michael Kors: (KORS)',info: 'O,.pyjxkne<br>1Q xjkxqs', hover:'Gtext<br>1Qlotatt<br>read more'},
{x: 20,y:50,ticker:'Soeuoeuoeu',info:'Doeuoeuoeull...<br><br>read more'},
{x:0,y:0,ticker:'Zynga: (ZNGA)'},
{x:3,y:4,ticker:'Avid: (AVID)'},
{x:30,y:10,ticker:'JCPenny: (JCP)'},
{x:29,y:25,ticker:'Deckers Outdoor: (DECK)'},
{x:25,y:5,ticker:'Zynga: (ZNGA)'},
{x:6,y:34,ticker:'Avid: (AVID)'},
{x:8,y:27,ticker:'JCPenny: (JCP)'},
{x:14,y:35,ticker:'Deckers Outdoor: (DECK)'},
{x:35,y:23,ticker:'Nutrisystem Corp: (NTRI)'},
]},
{name:'Strong Outlook (25)',color:'green',data:[
{x:100,y:100,ticker:'The Gap: (GPS)'},
{x:72,y:82,ticker:'Sodastream Intl: (SODA)'},
{x:82,y:74,ticker:'Under Armour: (UA)'},
{x:71,y:90,ticker:'Intuitive Surgical: (ISRG)'},
{x:88,y:69,ticker:'McDonalds: (MCD)'},
{x:95,y:87,ticker:'Lumber Liquidators: (LL)'},
{x:77,y:91,ticker:'Apple: (AAPL)'},
{x:96,y:78,ticker:'Walgreen Company: (WAG)'}, {x:100,y:100,ticker:'The Gap: (GPS)'},
{x:73,y:72,ticker:'Sodastream Intl: (SODA)'},
{x:84,y:74,ticker:'Under Armour: (UA)'},
{x:91,y:80,ticker:'Intuitive Surgical: (ISRG)'},
{x:68,y:93,ticker:'McDonalds: (MCD)'},
{x:95,y:67,ticker:'Lumber Liquidators: (LL)'},
{x:76,y:67,ticker:'Apple: (AAPL)'},
{x:79,y:84,ticker:'Walgreen Company: (WAG)'},
]},
{name:'Inline Company Performance (23)',color:'darkgrey',data:[
{x:40,y:44,ticker:'GIII'},
{x:53,y:43,ticker:'BNNY'},
{x:55,y:49,ticker:'SNE'},
{x:57,y:58,ticker:'WTW'},
{x:60,y:60,ticker:'LULU'},
{x:70,y:66,ticker:'FB'},
{x:51,y:24,ticker:'GIII'},
{x:45,y:26,ticker:'FB'},
{x:43,y:53,ticker:'BNNY'},
{x:47,y:59,ticker:'SNE'},
{x:51,y:48,ticker:'WTW'},
{x:56,y:40,ticker:'LULU'},
{x:59,y:52,ticker:'FB'},
{x:0,y:100,ticker:'Nutrisystem Corp: (NTRI)'},
]},
]
});
});
If allowMultipleInstances is set to false, opened expanders will close when you click to open another. Add this right after the included highslide.config.js file:
<script type="text/javascript">
hs.allowMultipleInstances = false;
</script>

Categories

Resources