Highcharts: send chart object as Javascript variable? - javascript

I want a Javascript function that will build different Highcharts when I send the charts as a variable. This is because my users can draw and redraw charts with triggers. My question is similar to this one except I want to pass all the chart parameters to the function and I want to call the function onload and when certain buttons are clicked.
How to create highcharts dynamically on click buttons

After doing more reading, I think this will work:
<script>
var options = {
chart: {
renderTo: 'container',
type: 'bar'
},
series: [{
name: 'Jane',
data: [1, 0, 4]
}]
};
function draw() {
new Highcharts.Chart(options);
}
jQuery( document ).ready(function() {
draw();
});

Related

Highcharts get table from range selected only

I am writting this highchart in angular and I want to create my own range selector dynamically using this.chart.update. However it keeps saying undefined update not a function. How can I fix the code. Also, I am trying to export the dataTable into the graphTable div which is into a differnt tab. I have attached a image please help. [graph/tableview image][1]
You can try to get the data from the range selector events rangeSelector.buttons.events, you can also set your own datagrouping with rangeSelector.buttons.dataGrouping.
rangeSelector: {
buttons: [{
type: 'month',
count: 1,
text: '1m',
events: {
click: function () {
console.log(this);
}
}
},
}
Demo:
https://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/stock/rangeselector/button-click/
API References:
https://api.highcharts.com/highstock/rangeSelector.buttons.events
https://api.highcharts.com/highstock/rangeSelector.buttons.dataGrouping
Implement inside chart.events.load() with this you are already close to getting data from other variables/sources and passing it inside the rangeSelector button events.
chart: {
events: {
load: function() {
let chart = this,
rangeSelector = chart.rangeSelector;
console.log(chart);
rangeSelector.update({
buttons: [{
Demo:
https://jsfiddle.net/BlackLabel/Lgdhokfy/
API References:
https://api.highcharts.com/highcharts/chart.events.load

Converting Poloniex API Callback JSON into format suitable for Highcharts.Stockchart

I am trying to get JSON from Poloniex's public API method (specifically the returnChartData method) to display chart history of cryptocurrencies against one another into a Highchart Stockchart graph (looking like the demo one here.).
This is part of my JavaScript code to use the Poloniex returnChartData callback, get the JSON from it and implement it into the 'data' segment of the chart. So far it is not working and I can't for the life of me figure out what I need to change.
var poloniexUrl = "https://poloniex.com/public?command=returnChartData&currencyPair=BTC_XMR&start=1405699200&end=9999999999&period=14400";
$.getJSON(poloniexUrl, function(data){
results = data;
});
// Creates Chart
var chart = new Highcharts.StockChart({
chart: {
renderTo: 'cryptoChart',
backgroundColor: 'white'
},
title: {
text: currentTitle
},
series: [{
data: results,
turboThreshold: 1000
}],
xAxis: {
original: false
},
rangeSelector: {
selected: 1
},
plotOptions: {
line: {
gapSize: 2
}
}
});
Would love any help!
Refer to this live demo: http://jsfiddle.net/kkulig/0f4odg5q/
If you use turboThreshold the points' options need to be given as an integer or an array (Explanation: https://api.highcharts.com/highstock/plotOptions.series.turboThreshold). In your case the format is JSON, so I disabled turboThreshold to prevent Higcharts error 12 (https://www.highcharts.com/errors/12):
turboThreshold: 0
$.getJSON is asynchronous - the best way to make sure that data variable is initialized is using it inside callback function (second argument of getJSON):
$.getJSON(poloniexUrl, function(data) {
// Creates Chart
var chart = new Highcharts.StockChart({
chart: {
(...)
The data that you fetch looks like candlestick series - I changed the type of the series:
type: 'candlestick'
Date will be properly understood by Highcharts if it's kept in the x property of JSON object (not date):
data: data.map((p) => {
p.x = p.date;
return p
}),

Accessing a previously drawn plot in javascript/jquery

I draw a plot like this:
var items = $.get("./moonlight_sonata_diameter.data", function(data) {
items = data.split(/\r?\n/).map( pair => pair.split(/\s+/).map(Number) );
$(function () {
plot = $.plot($("#placeholder"),
[ { data: linePoints} ], {
series: {
lines: { show: true }
},
crosshair: { mode: "x" },
grid: { hoverable: true, autoHighlight: false },
yaxis: { min: 0, max: 5 }
});
});
});
Now at a later moment in time, I want to update the crosshair of the plot. However, because it is embedded in so many functions, I don't know how to access it as I am not familiar with jQuery.
Within the script, I can run:
plot.setCrosshair({x: 100})
However, in another script, at another time, there is no object called plot. Is there a way to access it still?
Actually you have put your plot creation code in document ready function and your
plot.setCrosshair({x:100}) is executed just before your plot creation code. so A simple settimeout will do the trick.
just replace
plot.setCrosshair({x: 4})
with
setTimeout(function(){ plot.setCrosshair({x: 41})}, 3000);
and this will work fine. if you call your setCrosshair function after loading the complete dom then you will not need of setTimeout function. I hope this will help and if not then let me know.
Check it at http://plnkr.co/edit/3cMHmzWEIk6c39mblb0Z?p=preview

Custom Highcharts Context Menu Button Appearing in Every Chart on Page

I have a page with several charts, and I need to be able to add specific options to the exporting context menu for each chart. This is the code I am using:
myChart.options.exporting.buttons.contextButton.menuItems.push({
text: "Custom Option",
onclick: someFunction
});
Unfortunately, this adds the option to every chart, not just the chart myChart references. I'd like to be able to add an option and have it appear on only one chart.
Here is a fiddle which demonstrates: http://jsfiddle.net/4uP5y/2/
Thanks!
To add button use options for chart. Then you can set for each chart different set of options: http://jsfiddle.net/4uP5y/4/
Get default buttons:
var buttons = Highcharts.getOptions().exporting.buttons.contextButton.menuItems;
buttons.push({
text: "Tokyo Only Option",
onclick: HelloWorld
});
And set them for a chart:
exporting: {
buttons: {
contextButton: {
menuItems: buttons // or buttons.slice(0,6)
}
}
},
See the updated fiddle with result : http://jsfiddle.net/4uP5y/3/
You just needed to mark the newYork chart with exporting enabled false, like this :
exporting: {
enabled: false
}
Starting from Paweł Fus answer, I found out a cleaner solution for the general case. The main issue is you need not to mess around with original object and extend it. Instead, you'd be better cloning it. Please note that my solution requires jQuery.
function appendExportButton(mytext, myfunction){
var defaultButtons = Highcharts.getOptions().exporting.buttons; // get default Highchart Export buttons
var myButtons = $.extend(true, {}, defaultButtons);
myButtons.contextButton.menuItems.push({
text: mytext,
onclick: myfunction
});
return {buttons: myButtons};
}
To insert this button in the desired chart, define the chart this way:
var mychart = new Highcharts.Chart({
chart: {
...whatever...
},
plotOptions: {
...whatever...
},
series: {
...whatever...
},
exporting: appendExportButton("Save data in CSV format", saveCSV)
});
In the case of OP problem, this is the line you have to use:
exporting: appendExportButton("Tokyo Only Option", HelloWorld)
JSFiddle
I found another possiblity to add it only to one chart. Add following to the chart where you want to extend the context menu
exporting: {
buttons: {
contextButton: {
menuItems: [
]
}
}
},
.
Now you are able to extend the chart dynamicly with a method like
function (button) {
var userMenu = this.chart.userOptions.exporting.buttons.contextButton.menuItems;
if (userMenu.length === 0) {
var menuItems = Highcharts.getOptions().exporting.buttons.contextButton.menuItems;
for (var itemIndex in menuItems) {
userMenu.push(menuItems[itemIndex]);
}
}
userMenu.push(button);
};
. Where this.chart points to the chart which context menu should be extended

Javascript Unresponsive Script Error

I am trying to get data to load on my chart from an API. All the data is getting to the chart correctly, but the chart doesn't load and I get the unresponsive script error. I'm using Highcharts. Any suggestions? Thanks. My code is below.
Model
public function ajax_get_chart() {
$quotes = $this->rest->get('api/1/BTCUSD/trades/fetch');
$series_data = array();
$results = $quotes->return;
$i = 0;
foreach ($results as $quote)
{
$series_tmp = array(
'date' => $quote->date,
'price' => $quote->price
);
$series_data[]= $series_tmp;
$i= $i+1;
}
die (json_encode($series_data));
return TRUE;
}
Javascript
$(document).ready(function() {
var chart;
$.ajax({
url: "/chart/ajax_get_chart", // the URL of the controller action method
dataType: "json",
success: function(result)
{
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'bar'
},
title: {
text: 'Stacked bar chart'
},
xAxis: {
title: {
text: 'Price'
}
},
yAxis: {
min: 0,
title: {
text: 'Date'
}
},
legend: {
backgroundColor: '#FFFFFF',
reversed: true
},
tooltip: {
formatter: function() {
return ''+
this.series.name +': '+ this.y +'';
}
},
plotOptions: {},
series: result
});
}
});
});
Sounds like the problem is that there's too much data to present.
You can try using a speedier browser (Chrome usually works pretty fast), limiting the data, or trying another charting library.
Limiting the data is probably the most likely one to work. If you need to show all the data, the best way to go about it would be to only load partial data and then if the user for example scrolls the chart, load the missing data.
Another way to present more data at the same time would be to calculate averages for the data on server. For example, if the ticker data is from every second, you could pre-calculate hourly or even daily averages on the server. This generally allows you to show a relatively accurate chart without causing performance problems, and many libraries also support dynamically loading more accurate data if you zoom the chart.
Highcharts can not handle so huge number of data, but using Highstock with dataGrouping or lazy-loading you should be able to handle a lot of points, see demo.
Also this article should help.

Categories

Resources