setData is not a function + Angular2-Highcharts - javascript

I was following simple example to set data to Highcharts using this Angular2-Highcharts module
As shown in the following example, i have made small tweak to dynamically set data to Highcharts. Following is the code snippet :
constructor() {
this.options = {
chart: { type: 'spline' },
title: { text : 'dynamic data example'},
series: [{ data: [2,3,5,8,13] }]
};
setTimeout(() => {
this.chart.series[0].setData([21,31,51,81,13]);
}, 3000);
setTimeout(() => {
this.chart.series.push({data:[]});
this.chart.series[1].setData([100,200,300]);
}, 5000);
}
Plunker link for the same .
Error :
ERROR TypeError: _this.chart.series[1].setData is not a function
at eval (run.plnkr.co/QZBbWi3BVy3DeOzT/app/main.ts!transpiled:28)
My Observation :
What is evident with that error is there is no setData function in the series array in the 1st element. Alternate approach to resolve this is, initializing this.options with empty object with data property :
constructor() {
this.options = {
chart: { type: 'spline' },
title: { text : 'dynamic data example'},
series: [{ data: [2,3,5,8,13] },
{ data: [] },
]
};
}
This is very crude way as i need to do the same for 50 elements in this.options.series if i see them coming dynamically
Is there any efficient and better approach to resolve this error ?
PS : Am new to Highcharts, so please bear with me if am doing something completely wrong at basic level.

setData modifies a series which already exists - if you do not have the series you cannot modify it.
If you want to add a new series, you should use chart.addSeries() method like this:
setTimeout(() => {
this.chart.addSeries({
data: [21,31,51,81,13]
});
}, 5000);
example: http://plnkr.co/edit/61IgH8t3YKjtIOgzpUPB?p=preview

Related

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
}),

When does angular2 #output resolve?

Consider this plunker
HTML
<chart [options]="options"
(load)="saveGraphInstance($event.context)"></chart>
<div (click)="switchGraph()">switch</div>
<div (click)="showLoadingForce()">show loading</div>
Typescript
class AppComponent {
constructor() {
this.options = {
title : { text : 'simple chart' },
series: [{
data: [29.9, 71.5, 106.4, 129],
}],
lang:{
loading: 'your text here',
},
};
}
options: Object;
graph: any;
switchGraph() {
this.options = {
title : { text : 'different chart' },
series: [{
data: [129.9, 171.5, 106.4, 129],
}],
lang:{
loading: 'your text here',
},
};
this.graph.showLoading() // This doesn't work
setTimeout(function() {
this.graph.showLoading() // This also doesn't work
}, 4000);
}
showLoadingForce() {
this.graph.showLoading() // User clicked work
}
saveGraphInstance(graph) {
this.graph = graph;
//this.graph.showLoading() // after loading work
}
}
We see from the above code that in the same function that option change, show loading does not work even if I set time out for more than 4 second
But if its done after load trigger or user initiated, then it always work.
This is very interesting, so my question is the following
If I click switch div and immediately click show loading div, the loading text will show, then the setimeout will execute (because 4 sec delay), but only the setimeout will run into error ERROR TypeError: Cannot read property 'showLoading' of undefined. How is that possible? If showLoadingForce is successful that means saveGraphInstance must have happened
When is (load) execute and resolve? I cannot find the relevant information in github source code
Regarding Q1,
ERROR TypeError: Cannot read property 'showLoading' of undefined
This is an issue with accessing this inside setTimeout(). Inside the setTimeout method this default to window object. To fix this pass the save the the reference to this then access it in setTimeout method.
Refer to the "this" problem.
Regarding Q2, load is defined as output ChartEvent binding in the ChartComponent. This will invoke new instance of EventEmitter.
Use following code to hide the loading image after setTimeout: Updated plunker
saveGraphInstance(graph) {
this.graph = graph;
this.graph.showLoading();
var that = this;
setTimeout(function(graph) {
that.graph.hideLoading();
}, 4000);
}
JS API Reference

Highcharts error csv.replace is not a function

I'm working on parsing some data from a CSV file, but i get this error :
Uncaught TypeError: csv.replace is not a function
I don't know why, can somebody help me ?
This is my loadCSV.js:
jQuery(document).ready(function($) {
var parse;
var csv = Papa.parse("http://1001dev.com/Chahine/wp-content/themes/consulting-child/fonds/DigitalStarsEurope/volatilityFR.csv", {
download: true,
complete: function(results) {
console.log(results.data);
$("#EuropeVolatilityBtn").click(function() {
$('#EuropeVolatility').highcharts({
data: {
csv: results
}
});
});
}
});
});
You can see the result here in :
http://1001dev.com/Chahine/fonds/
When you click on the button : Volatilité the message appear.
Thanks a lot,
Cheers,
Jordan
You've already parsed your CSV file into json using Papa.parse. Highcharts data is looking for a CSV string, not a json object.
Also, why are you fetching the CSV file outside the click handler? The CSV will be downloaded even if the user never clicks on that button.
See: https://www.highcharts.com/docs/working-with-data/data-module
$.get('data.csv', function(csv) {
$('#container').highcharts({
chart: {
type: 'column'
},
data: {
csv: csv
},
title: {
text: 'Fruit Consumption'
},
yAxis: {
title: {
text: 'Units'
}
}
});
});
In addition to what #Barbara said, you can use Highcharts data module and parse your data adequately inside complete function. Take a look at the example posted below.
API Reference:
http://api.highcharts.com/highcharts/data.complete
Example:
http://jsfiddle.net/ny0qh8o3/

Chart data not exporting completely

I am trying to export a dataset from the chart, one of the lines should be started from the second x-axis point. I.e. dataset looks like
var dataset = [
{ dept2:26, m:"Jan" },
{ dept1:30, dept2:38, m:"Feb" },
{ dept1:61, dept2:54, m:"Mar" },
{ dept1:65, dept2:67, m:"Apr" },
{ dept1:74, dept2:69, m:"May" },
{ dept1:74, dept2:69, m:"Jun" },
{ dept1:74, dept2:69, m:"Jul" }
];
Full snippet: http://webix.com/snippet/457ffa4e
But toExcel method in Webix won't export column without the first value. How can I overcome that?
Try to define your output in this way:
webix.toExcel($$("chart"), {
columns:{
"dept1":true,
"dept2":true,
"m":true
}
});
Snippet

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