HighChart Line Graph not Showing - javascript

I am using data from a csv file to generate a line graph using Highchart. Here is my code:
/* Define Initial and basic Options */
var options = {
chart: {
type: 'line',
renderTo: 'graph_container'
},
title: {
text: 'FanniemaeAcquisition Cash Flow'
},
yAxis: {
title: {
text: 'Amount($)'
}
},
series: []
};
/* Parse CSV File */
$.get('{% static "data/FanniemaeAcquisitions.csv" %}', function(csv) {
var lines = csv.split('\n');
var series = {
name: '',
data: []
};
$.each(lines, function (lineNo, line) {
var items = line.split(',');
$.each(items, function (itemNo, item) {
if(itemNo == 1){
if (lineNo == 0){
series.name = item;
} else {
series.data.push(parseFloat(item));
}
}
});
});
options.series.push(series);
console.log(options.series);
});
// Create the chart
var chart = new Highcharts.Chart(options);
However this isn't working. I tried testing it by manually inputting data like so:
series: [{
name: 'Installation',
data: [43934, 52503, 57177, 69658, 97031, 119931, 137133, 154175]
},
and that works fine. So I took a look at the variables being passed to series. The one that works(manual input):
The one that doesn't work(From CSV):
Any ideas?
EDIT: Okay. something weird is going on here. Highchart isn't showing on the webpage but it showing when I download as PNG. The weirder part is that it shows on the webpage if I MANUALLY add in number values but when I extract the values form CSV the graph disappears... But when I download as PNG it shows the graph...Any ideas??
SECOND EDIT: Okay, so when I do: console.log(JSON.stringify(options.series[0].data));
nothing shows up. This would mean that the values parsed from the csv file appear after the graph is generated. So how do I fix this? lol

The problem was due to Javascript's Asynchronous Issues. I simply wrapped my function in a $.when and it worked!

Related

Show Labels on Pie pieces instead of Data values Chart.js

I use Chart.js for making charts. I discovered today new plugin for the original Chart.js.
Plugin
After i added <script> tags with the plugin, it applied automatically values to all my charts. It looks great, but it shows number values. How do i make it show labels instead of values on the pieces of the pie? I have found some posts about the subject, but they contain different commands, and i tried all i could but it didn't change anything. Also for the future, tell me please how to turn off showing values for specific chart :)
fillPie()
{
// Three arrays have same length
let labelsArr = []; // Array with some names
let values = []; // Array with values
let randomColor = [];
var ctx = document.getElementById('pie-chart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'pie',
// The data for our dataset
data: {
labels: labelsArr, // I want it to show these labels
datasets: [{
backgroundColor: randomColor,
data: values, // It shows these values
hoverBackgroundColor: "#fba999"
}]
},
// Configuration options go here
options: {
legend: {
display: false
}
}
});
}
You can find the answer in the docs of the plugin:
https://chartjs-plugin-datalabels.netlify.com/guide/formatting.html#custom-labels
options: {
plugins: {
datalabels: {
formatter: function(value, context) {
return context.chart.data.labels[context.dataIndex];
}
}
}
}
The dev simonbrunel explained on GitHub how you can disable the plugin globally or for specific datasets. The following is a quote from the GitHub link:
That should be possible by disabling labels for all datasets via the plugin options at the chart level using the display option, then enable labels per dataset at the dataset level (dataset.datalabels.*):
new Chart('id', {
data: {
datasets: [{
// no datalabels for this dataset
}, {
datalabels: {
// display labels for this specific dataset
display: true
}
}
},
options: {
plugins: {
datalabels: {
// hide datalabels for all datasets
display: false
}
}
}
})
You can also globally disable labels for all charts using:
// Globally disable datalabels
Chart.defaults.global.plugins.datalabels.display = false

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

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/

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.

Parsing JSON data for Highcharts

I have been going in circles for a few hours with this and have exhausted all the similar stackoverflow threads and also highcharts docs, so hopefully someone can help.
I am trying to plot a pie chart with a gender split. I have worked with line charts before and so had my data in the format for x and y axis, like this:
[{"y":"Mr","x":"145"},{"y":"Miss","x":"43"},{"y":"Mrs","x":"18"},{"y":"Ms","x":"2"}]
This was getting me somewhere, i could tap into the json and pull out the ints but i couldnt for the life of me get the titles associated with the figures...
function genderData() {
$.getJSON('/statsboard/gender', function(data_g) {
$.each(data_g, function(key_g, val_g) {
obj_g = val_g;
genderChart.series[0].addPoint(parseInt(obj_g.x));
//genderChart.xAxis[0].categories.push(obj_g.y);
});
});
}
I then just called the function genderData as follows:
genderChart = new Highcharts.Chart({
chart: {
renderTo: 'gender',
events: {
load: genderData
}
}
title: {
text: 'Gender Split'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
},
},
series: [{
type: 'pie',
name: 'Gender Split',
data: []
}]
});
So i ended up with an accurate chart but with out the labels, and they would just default to 'slice'...
So close but no cigar ;-)
Soooo i altered my serverside code to return the following format as per the docs :-), now returning the following:
[{"Mr":"145"},{"Miss":"43"},{"Mrs":"18"},{"Ms":"2"}]
This looks pretty much spot on to me, but alas, when i try to accomodate for this on the js code, everything falls apart.
I have been looking at this:
Write JSON parser to format data for pie chart (HighCharts)
but cant get the practice applied here to fit my circumstances.. Can anyone help?
The forms:
[{"name": "Mr", "y": 145}, ...]
or
[["Mr", 145], ...]
will work. Notice the second form is an array of arrays not an array of objects (you were close).
See basic-pie demo (click view options and scroll down to data), series.data docs, and series.addPoint docs for more info.
If you make the server side return the data in one of the two above forms you can just do:
function genderData() {
$.getJSON('/statsboard/gender', function(data_g) {
genderChart.series[0].setData(data_g, true);
});
}
You can set your points as follows:
genderChart.series[0].addPoint({
name: key_g,
y: val_g
});
By rearranging my Json to have "name" and "y" as the keys i was able to make progress i.e:
[{"name":"Mr","y":"145"},{"name":"Miss","y":"43"},{"name":"Mrs","y":"18"},{"name":"Ms","y":"2"}]
Then by looping through the json data and parsing the "y" value as a int with the function parseInt() in the JS i was able to get my desired result...
function genderData() {
$.getJSON('/statsboard/gender', function(data_g) {
$.each(data_g, function(key_g, val_g) {
obj_g = val_g;
genderChart.series[0].addPoint({
name: obj_g.name,
y: parseInt(obj_g.y)
});
console.log(obj_g.y)
});
});
}
I know this question has been solved. but the map function for array might be a good choice in these cases, I love map in functional language!
data = [{"y":"Mr","x":"145"},{"y":"Miss","x":"43"},
{"y":"Mrs","x":"18"},{"y":"Ms","x":"2"}];
var series = data.map(function(e){ return parseInt(e.x); });
.... hight chart ....

Categories

Resources