Loading JQuery dynamically but highcharts fails - javascript

I am not really a javascript programmer but I have been struggling for a long time with this problem - any help would be very much appreciated.
In the following jsfiddle - if Jquery is selected from the frameworks and extensions tab the highcharts chart works fine. But the point of the code is I need to dynamically load a different jquery version - to use the chart as a widget of sorts. But changing it to no library (pure JS) the chart does not load.
http://jsfiddle.net/hgera000/JcVLQ/3/
A large part of my code I'm getting from here:
http://alexmarandon.com/articles/web_widget_jquery/
Thanks very much
(function() {
// Localize jQuery variable
var jQuery;
/******** Load jQuery if not present *********/
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.7.2') {
var script_tag = document.createElement('script');
script_tag.setAttribute("type","text/javascript");
script_tag.setAttribute("src",
"http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js");
if (script_tag.readyState) {
script_tag.onreadystatechange = function () { // For old versions of IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
scriptLoadHandler();
}
};
} else {
script_tag.onload = scriptLoadHandler;
}
// Try to find the head, otherwise default to the documentElement
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
} else {
// The jQuery version on the window is the one we want to use
jQuery = window.jQuery;
main();
}
/******** Called once jQuery has loaded ******/
function scriptLoadHandler() {
// Restore $ and window.jQuery to their previous values and store the
// new jQuery in our local jQuery variable
jQuery = window.jQuery.noConflict(true);
// Call our main function
main();
}
/******** Our main function ********/
function main() {
var chart;
jQuery(document).ready(function($) {
/******* Load CSS *******/
var css_link = $("<link>", {
rel: "stylesheet",
type: "text/css",
href: "style.css"
});
css_link.appendTo('head');
/******* Load HTML *******/
chart = new Highcharts.Chart({
credits: {
enabled: true,
text: '',
href: ''
},
chart: {
renderTo: 'bm-container',
events: {
click: function () {
window.open('http://www.betmetrix.com', '_blank')
},
},
backgroundColor: '#FFFFFF',
zoomType: 'xy',
type: 'line',
marginLeft: 40,
marginRight: 40,
marginBottom: 40,
},
title: {
text: 'Election Worm',
x: -5,
style: {
color: '#000000',
fontWeight: 'bold',
fontSize: '17pt'
}
},
subtitle: {
text: 'Estimated Probability of Victory',
x: -5,
style: {
color: '#000000',
//fontWeight: 'bold',
fontSize: '13pt'
}
},
xAxis: {
type: 'datetime',
minRange: 7 * 24 * 3600000, // 1 week
dateTimeLabelFormats: {
second: '%H:%M:%S',
minute: '%H:%M',
hour: '%H:%M',
day: '%e %b',
week: '%e %b',
month: '%b \'%y',
year: '%Y'
},
//max: lnp[lnp.length-1][0]+604800000,
//tickInterval: 24*3600*1000*120,
//showFirstLabel: false,
minTickInterval: 1 * 24 * 3600000, //1 day
//maxTickInterval: 1 * 24 * 3600000*365, //30 day
startOnTick: false,
labels: {
style: {
color: '#969696',
//fontWeight: 'bold',
fontSize: '11pt'
}
}
},
yAxis: [{
//LHS axis
title: {
text: '%',
align: 'high',
rotation: 0,
offset: 10,
style: {
color: '#969696',
//fontWeight: 'bold',
fontSize: '11pt'
}
},
labels: {
style: {
color: '#969696',
//fontWeight: 'bold',
fontSize: '11pt'
}
},
showLastLabel: false,
showFirstLabel: false,
minRange: 3,
minTickInterval: 1,
min: 0,
max: 100,
opposite: false,
startOnTick: true,
//tickInterval: 5,
allowDecimals: false
}, {
//RHS axis
title: {
text: '%',
align: 'high',
rotation: 0,
offset: 20,
style: {
color: '#969696',
//fontWeight: 'bold',
fontSize: '11pt'
}
},
linkedTo: 0,
labels: {
style: {
color: '#969696',
//fontWeight: 'bold',
fontSize: '11pt'
}
},
showLastLabel: false,
minTickInterval: 1,
minRange: 3,
showFirstLabel: false,
startOnTick: true,
min: 0,
max: 100,
opposite: true,
//tickInterval: 10,
allowDecimals: false
}],
tooltip: {
xDateFormat: '%d-%b-%Y %l%P', //'%d-%b-%Y %l%P'
valueSuffix: '%',
valueDecimals: 1
//formatter: function () {
// return this.x + '<br/><b>' + this.series.name + ':' + '</b>' + this.y + '%';
//}
},
legend: {
enabled: false
// layout: 'vertical',
// align: 'right',
// verticalAlign: 'left',
// x: -20,
// y: 10,
// borderWidth: 0
},
series: [{
name: 'Coalition',
data: lnp,
marker: {
enabled: false
},
yaxis: 0
}, {
name: 'ALP',
data: alp,
marker: {
enabled: false
},
yaxis: 0
}],
exporting: {
enabled: false
}
});
});
}
})(); // We call our anonymous function immediately

Although the alexmarandon.com web widget tutorial mentions other libraries, maybe your case would be better suited with an all dynamic "chain load" approach. Once the jquery dynamic load is complete, don't go directly to main(), but instead move on and chain load Highcharts dynamically as well. Add this one more function, remove static, external reference to Highcharts.js, and then replace the call back to scriptLoadHandler() with a call to this chainLoadHighchharts() function, which itself will then pass on to the original scriptLoadHandler().
function chainLoadHighCharts() {
var Highcharts;
/******** Ok, /now/ dynamically load up highchart too... *********/
if (window.Highcharts === undefined) {
var script_tag = document.createElement('script');
script_tag.setAttribute("type", "text/javascript");
script_tag.setAttribute("src",
"http://code.highcharts.com/highcharts.js");
if (script_tag.readyState) {
script_tag.onreadystatechange = function () { // For old versions of IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
scriptLoadHandler(); //here is the call that was orginally called directly from the jquery dynamic load.
}
};
} else {
script_tag.onload = scriptLoadHandler;
}
// Try to find the head, otherwise default to the documentElement
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
} else {
scriptLoadHandler();
// script_tag.setAttribute("src","http://code.highcharts.com/modules/exporting.js");
}
}
Still needs a bit of tightening, but it ran without error for me on jsfiddle.
http://jsfiddle.net/JcVLQ/5/

Related

Highcharts not showing up in ruby web app

Will someone tell me why my high charts aren't coming up on my ruby sinatra web application. I'm trying to pull data from my dynamodb table and put that into charts. I downloaded my dynamodb items into a csv then converted that to a json file hoping that would help. I can go on high charts website and do a demo and it loads in my website just not mine.
This is my synchronize-chart.js
$(function() {
$('#synchronized').bind('mousemove touchmove', function(e) {
var chart,
point,
i;
for (i = 0; i < Highcharts.charts.length; i = i + 1) {
chart = Highcharts.charts[i];
if(chart.renderTo.className != 'chart'){
continue;
}
e = chart.pointer.normalize(e); // Find coordinates within the chart
point = chart.series[0].searchPoint(e, true); // Get the hovered point
if (point) {
point.onMouseOver(); // Show the hover marker
chart.tooltip.refresh(point); // Show the tooltip
chart.xAxis[0].drawCrosshair(e, point); // Show the crosshair
}
}
});
/**
* Override the reset function, we do not need to hide the tooltips and crosshairs.
*/
Highcharts.Pointer.prototype.reset = function() {
return undefined;
};
/**
* Synchronize zooming through the setExtremes event handler.
*/
function syncExtremes(e) {
var thisChart = this.chart;
if (e.trigger !== 'syncExtremes') { // Prevent feedback loop
Highcharts.each(Highcharts.charts, function(chart) {
if (chart !== thisChart) {
if (chart.xAxis[0].setExtremes) { // It is null while updating
chart.xAxis[0].setExtremes(e.min, e.max, undefined, false, {
trigger: 'syncExtremes'
});
}
}
});
}
}
// Get the data. The contents of the data file can be viewed at
// https://github.com/highcharts/highcharts/blob/master/samples/data/activity.json
$.getJSON('/covertcsv.json', function(activity) {
$.each(activity.datasets, function(i, dataset) {
// Add X values
dataset.data = Highcharts.map(dataset.data, function(val, j) {
return [activity.xData[j], val];
});
$('<div class="chart">')
.appendTo('#synchronized')
.highcharts({
chart: {
marginLeft: 40, // Keep all charts left aligned
spacingTop: 20,
spacingBottom: 20,
zoomType: 'x'
},
title: {
text: dataset.name,
align: 'left',
margin: 0,
x: 30
},
credits: {
enabled: false
},
legend: {
enabled: false
},
xAxis: {
crosshair: true,
events: {
setExtremes: syncExtremes
},
type: 'datetime'
},
yAxis: {
title: {
text: null
}
},
tooltip: {
positioner: function() {
return {
x: this.chart.chartWidth - this.label.width, // right aligned
y: -1 // align to title
};
},
borderWidth: 0,
backgroundColor: 'none',
//pointFormat: '{point.y}',
pointFormat: '<span style="font-size: 10px">{point.x:%e. %b \'%y %H:%M:%S}</span> {point.y}',
headerFormat: '',
shadow: false,
style: {
fontSize: '18px'
},
valueDecimals: dataset.valueDecimals
},
series: [{
data: dataset.data,
name: dataset.name,
type: dataset.type,
color: Highcharts.getOptions().colors[i],
fillOpacity: 0.3,
tooltip: {
valueSuffix: ' ' + dataset.unit
}
}]
});
});
});
});
Water-level-chart.js
$(function() {
var gaugeOptions = {
chart: {
type: 'solidgauge'
},
title: null,
pane: {
center: ['50%', '85%'],
size: '140%',
startAngle: -90,
endAngle: 90,
background: {
backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || '#EEE',
innerRadius: '60%',
outerRadius: '100%',
shape: 'arc'
}
},
tooltip: {
enabled: false
},
// the value axis
yAxis: {
stops: [
[0.1, '#DF5353'], // red
[0.5, '#DDDF0D'], // yellow
[0.6, '#55BF3B'] // green
],
lineWidth: 0,
minorTickInterval: null,
tickPixelInterval: 400,
tickWidth: 0,
title: {
y: -70
},
labels: {
y: 16
}
},
plotOptions: {
solidgauge: {
dataLabels: {
y: 5,
borderWidth: 0,
useHTML: true
}
}
}
};
$.getJSON('/convertcsv.json', function(data) {
// The speed gauge
$('#container-speed').highcharts(Highcharts.merge(gaugeOptions, {
yAxis: {
min: 0,
max: 500,
title: {
text: 'Water Level'
}
},
credits: {
enabled: false
},
series: [{
name: 'Water Level',
data: [data.waterLevel],
dataLabels: {
format: '<div style="text-align:center"><span style="font-size:25px;color:' +
((Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black') + '">{y}</span><br/>' +
'<span style="font-size:12px;color:silver">water left</span></div>'
},
tooltip: {
valueSuffix: ''
}
}]
})); // container-speed end
}); // getJson end
});
item.rb
class Item
require 'dynamoid'
include Dynamoid::Document
table name: :sensor, key: :key, :read_capacity => 5, :write_capacity => 5
field :timestamp, :integer
field :payload, :serialized
def self.chart_values
x_data = []
temperatures = []
humidities = []
soil_moistures = []
# not an efective way to do
Item.all.each do |item|
x_data << item.timestamp
temperatures << (item.payload['temp'].to_f || 0)
humidities << (item.payload['hum'].to_f || 0)
soil_moistures << (item.payload['sol'].to_f || 0)
end
highcharts_value(x_data, temperatures, humidities, soil_moistures)
end
def self.highcharts_value(x_axis, temp, hum, soil)
{
xData: x_axis,
datasets: [
{
name: 'Temperature',
data: temp,
unit: '°C',
type: 'area',
valueDecimals: 1
},
{
name: 'Humidity',
data: hum,
unit: '%',
type: 'area',
valueDecimals: 1
},
{
name: 'Soil Moisture',
data: soil,
unit: '',
type: 'area',
valueDecimals: 0
}
]
}
end
end
index.haml
%head
%script{type: "text/javascript", src: url('/javascripts/jquery.min.js')}
%script{type: "text/javascript", src: url('/javascripts/highcharts.js')}
%script{type: "text/javascript", src: url('/javascripts/highcharts-more.js')}
%script{type: "text/javascript", src: url('/javascripts/solid-gauge.js')}
%script{type: "text/javascript", src: url('/javascripts/synchronized-charts.js')}
%script{type: "text/javascript", src: url('/javascripts/water-level-chart.js')}
%script{type: "text/javascript", src: url('/javascripts/water-pump.js')}
%link{rel: :stylesheet, type: :"text/css", href: url('/stylesheets/default.css')}
#container
#synchronized
.gauge
#container-speed
.pump-control
%form{method: :post, action: '/take-action', id: 'action-form' }
%input{type: 'hidden', name: 'action', value: 'start', id: 'action_input'}
%span{id: 'pumper', onclick: 'takeAction()'}
start
After checking the browser console it says
jquery.min.js:2 GET http://localhost:4567/convertcsv.json 404 (Not Found)
send # jquery.min.js:2
ajax # jquery.min.js:2
p.(anonymous function) # jquery.min.js:2
getJSON # jquery.min.js:2
(anonymous) # synchronized-charts.js:60
k # jquery.min.js:2
fireWith # jquery.min.js:2
ready # jquery.min.js:2
D # jquery.min.js:2

Highchart: is it possible to change the font of the label in Highchart via a click of a button?

Link to JFiddle: http://jsfiddle.net/z24ysp8m/3/
Here is the code in concern:
$(function() {
var chartData = [-5, 5, -10, -20];
var timeStamps = [];
var index = 1;
var pWidth = 25;
$('#b').click(function(){
timeStamps.push(new Date());
var buttonB = document.getElementById('b');
buttonB.disabled = true;
/* if(index == 1){
$('#container').highcharts().xAxis[0].labels.style = {"color":"#6D869F","fontWeight":"bold"};
}*/
if(index <= chartData.length){
$('#container').highcharts().series[0].remove();
$('#container').highcharts().addSeries({pointPlacement: 'on', data: [chartData[index - 1]],
pointWidth: pWidth});
$('#container').highcharts().xAxis[0].setCategories([index]);
setTimeout(function(){index++;}, 2000);
}
if(index < chartData.length){
setTimeout(function(){buttonB.disabled = false;}, 1500);
}else{
setTimeout(function(){buttonB.style.visibility="hidden";}, 1500);
}
if(index == chartData.length - 1){
setTimeout(function(){document.getElementById('b').innerHTML = 'Lasst Period';}, 1500);
}
console.log(timeStamps);
})
// $(document).ready(function () {
Highcharts.setOptions({
lang: {
decimalPoint: ','
},
});
$('#container').highcharts({
chart: {
type: 'column',
width: 170,
marginLeft: 74,
marginRight: 16,
marginBottom: 60
},
title: {
text: ''
},
colors: [
'#0000ff',
],
xAxis: {
title: {
text: ''
// offset: 23
},
gridLineWidth: 1,
startOnTick: true,
tickPixelInterval: 80,
categories: ['Filler'], // used only to make sure that the x-axis of the two charts
// are aligned, not shown on the chart via setting the font color to white
min:0,
max:0,
labels: {
style: {
color: 'white'
}
}
},
yAxis: {
title: {
text: 'Value'
},
min: -20,
max: 20,
tickPixelInterval: 40
},
plotOptions: {
series: {
animation: {
duration: 1000
}
}
},
credits: {
enabled: false
},
tooltip: {
formatter: function () {
return Highcharts.numberFormat(this.y, 2) + '%';
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
data: [],
pointWidth: pWidth
}]
});
// });
});
I want that the x-axis has no label when the page is loaded (The reason why I added in a filler text with white font is due to the fact that I don't want the size of the chart change upon click of a button). And upon the click of button, the label should be consecutively 1, 2, 3, 4...
Is there anyway around it except for setting marginBottom (which is not very precise)?
You may use .css() method for changing fill color of your text label.
Here you can find information about this method:
http://api.highcharts.com/highcharts#Element.css
Highcharts.each($('#container').highcharts().xAxis[0].labelGroup.element.children, function(p, i) {
$(p).css({
fill: 'red'
});
});
And here you can find simple example how it can work:
http://jsfiddle.net/z24ysp8m/6/

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!

Getting error when try to use external parameter to generate chart

I retrieve JSON data from server and put it in Highchart as series.I am facing this error:
Error: Invalid value for attribute y="NaN" highcharts.js : 9
The error happen if I send chartSeries parameter from callChart function.But if I copy chartSeries value and put it directly inside drawChart it able to display the chart.However there no problem for other parameter such chartCategory and chartTitle.
Here is my code:
function callChart(){
for (var i in jsonData){
console.log('#i '+i);
console.log('#subSegment i '+jsonData[i].subSegment);
var chartTitle= jsonData[i].subSegment;
console.log('categories '+ jsonData[i].categories);
var chartCategory= jsonData[i].categories;
console.log('series '+ JSON.stringify(jsonData[i].series));
var chartSeries=JSON.stringify(jsonData[i].series);
drawChart($('.chartContainer'),chartSeries,chartCategory,chartTitle);
break;}}
Here is the code of drawChart;
function drawChart(container,chartSeries,chartCategory,chartTitle) {
console.log('# test');
console.log('# chartSeries='+chartSeries);
console.log('# chartCategory='+chartCategory);
console.log('# chartTitle='+chartTitle);
//it works if I put the chartSeries directly here
/*chartSeries=[{"type":"column","stack":null,"pointPlacement":null,"name":"HDD","linkedTo":null,"id":"hdd","data":[30,30,70,90,37,200],"color":"greenColor","borderWidth":null},{"type":"column","stack":"old","pointPlacement":null,"name":"SSHD","linkedTo":null,"id":"sshd","data":[0,100,40,90,60,90],"color":"yellowColor","borderWidth":null},{"type":"column","stack":"old","pointPlacement":null,"name":"SSD","linkedTo":null,"id":"ssd","data":[50,100,40,90,60,100],"color":"blueColor","borderWidth":null},{"type":"column","stack":"forecast","pointPlacement":null,"name":"HDD","linkedTo":"hdd","id":null,"data":[30,80,40,100,60,90],"color":"greenColor","borderWidth":null},{"type":"column","stack":"forecast","pointPlacement":null,"name":"SSD","linkedTo":"ssd","id":null,"data":[30,80,40,100,60,90],"color":"yellowCollor","borderWidth":null},{"type":"spline","stack":null,"pointPlacement":null,"name":"Share","linkedTo":null,"id":null,"data":[30,80,40,100,60,90],"color":"black","borderWidth":null}] ;
*/
if (!container.length) {
return;
}
var chart = new Highcharts.Chart({
tooltip: {
enabled: true
},
credits: {
enabled: false
},
chart: {
renderTo: container[0],
style: {
fontFamily: '"Arial", "Helvetica", "sans-serif"',
fontSize: '12px',
fontWeight: 'bold'
},
marginLeft:60,
marginRight:65
},
title: {
text: chartTitle
},
xAxis: {
categories: chartCategory
},
yAxis: [{
min: 0,
title: {
text: 'Units in 000\' s'
},
stackLabels: {
enabled: false,
style: {
fontWeight: 'bold',
color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
}
}
}, { // Secondary yAxis
title: {
text: 'Share',
style: {
color: Highcharts.getOptions().colors[0]
}
},
labels: {
format: '{value} %',
style: {
color: Highcharts.getOptions().colors[0]
}
},
opposite: true,
min: 0,
max: 100
}],
legend: {
enabled:false
},
plotOptions: {
column: {
grouping: false,
stacking: 'normal',
pointWidth:30
},
series:{shadow:false}
}
,series:chartSeries
});
}
Thanks alot.
Okay, I found it already.
Instead pass JSON.stringify(jsonData[i].series) , directly pass jsonData[i].series.
Thanks

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