CanvasJS - accessing variables - permission denied to access property toString - javascript

So, I have a form values of which I want to display in a chart. The code is as follows:
var chart;
function createChart() {
console.log($("#kok").val()); // this prints a number
try {
chart = new CanvasJS.Chart("chart", {
theme: "theme2",
title: {text:"Kannatus"},
data: [{
type:"column",
dataPoints: [
{label:"KOK", y:$("#kok").val()}, // the problem is here
{label:"KESK", y:$("#kesk").val()},
{label:"SDP", y:$("#sdp").val()},
{label:"PS", y:$("#ps").val()},
]
}]
});
} catch(e) {
console.log(e.message);
}
chart.render();
What's wrong here? Should I just use a different library?

Here the type of $("#kok").val() is string. Converting it to Number will help you out.
You can refer http://www.w3schools.com/js/js_type_conversion.asp

Related

Use variable as data in apexcharts

I'm trying to display a chart in apexcharts, and use a variable as the data. When I do this, nothing is displayed. See the following:
var message = '[1,4]'
var options = {
chart: {
type: 'line',
sparkline: {
enabled: true,
}
},
series: [{
data: message,
}],
}
var chart = new ApexCharts(document.querySelector("#chart"), options);
chart.render();
Using the variable message as data doesn't work. When I switch the line:
data: message,
to
data: [1,4]
it displays correctly. However, I must use a variable. How do I do this?
You declared message variable as STRING, It is expecting an ARRAY
Please change
var message = '[1,4]'
to
var message = [1,4];

Parsing JSON data into an array for a C3.js chart

I'm sending a json variable from django to C3.js in this format:
{
datetime.date(2015, 5, 1): 22792461.479999978,
datetime.date(2015, 6, 1): 24807797.38999998,
datetime.date(2015, 7, 1): 25261456.609999962
}
I need to extract the values and compile them into an array ready for use by c3.js. Here's my script:
<script>
{% include "croydon_dashboards/dashboard_includes/gb_locale.html" %}
var row_value = {{ row_value }};
var sum_list = [];
for(var i in row_value)
sum_list.push(row_value[i])
sum_list = JSON.stringify(sum_list);
var chart = c3.generate({
data: {
columns: [
sum_list
],
type: 'bar'
},
bar: {
width: {
ratio: 0.5
}
}
});
</script>
Hard coding values into the chart works, so I know the c3.js is right, but there's something wrong with the way I'm building the array.
I know that there's an answer here: JSON Data doesn't show on c3.js bar chart
but I'm new to javascript and can't work out how to parse the json that I'm working with.
You do not need to JSON.stringify() your data to use it with c3.
But you may have to JSON.parse() it to make it look like this:
var row_value = {
"2015-05-01": 22792461.479999978,
"2015-06-01": 24807797.38999998,
"2015-07-01": 25261456.609999962
};
And don't forget to add text label at the beginning of data array:
// This first value of array if the name of your data
var sum_list = ['something'];
The rest of your code works.
for(var i in row_value)
sum_list.push(row_value[i])
var chart = c3.generate({
data: {
columns: [
sum_list
],
type: 'bar'
},
bar: {
width: {
ratio: 0.5
}
}
});
See this fiddle.

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

To create piechart in highcharts

Below is my JSON format of data from which I want to create a pie chart in highcharts..
{
"title": {"text": "Pie"},
"series":
[
{
"type": "pie",
"name": "Actual",
"data":
[
[
"Salesgrowth",
45
],
[
"marketshare",
26.8
]
]
}
]
}
This is valid JSON , I am getting this output from Web Service, when I call this service and evoke this method to run this JSON output to create pie then I get the error as follows,
Uncaught TypeError: Cannot set property 'renderTo' of undefined
Below is the JQuery function that I make use to call my file where I stored this JSON output from my web service,
function loadJson() {
$(document).ready(function () {
//alert("inside");
var chart;
var seriesData;
$.getJSON("val1.json", function (data) {
var chartoptions = data;
chartoptions.chart.renderTo = 'container';
chart = new Highcharts.Chart(chartoptions);
});
});
},
and this function runs well with other kind of charts like bar graph,line graph and column graph...tested with all kinds of graphs, I am facing problem only with pie chart...any help will be greatly appreciated
---------Updated question------
Below is my JSON output I have changed in order to get values
{
"title":{"text":"Financial"},
"chart":{"type":"pie"},
"series":
[ {"name":"Actual-Market Share","data":["Market Share",30]},{"name":"Actual-Market Share","data":["Sales Growth",70]}]}
and below is the output I am getting,
I am not able to identify what I am exactly messing with...Any idea will be of great help...
----------Updated output-----------
{
"legend":{"enabled":"true"},
"title":{"text":"Financial"},
"chart":{"type":"pie"},
"series":[{"name":"Actual","data":[{"str":"Market Share","flo":20}]},
{"name":"Actual","data":[{"str":"Sales Growth","flo":30}]},
{"name":"Actual","data":[{"str":"Operating Profit","flo":40}]},
{"name":"Actual","data":[{"str":"Gross Margin %","flo":10}]}]}
Your json doesn't include a chart object, so setting chart.renderTo won't work.
If you can change the webservice, get it to add the following to your json:
chart: {
},
If you can't change the back end, you can change your javascript to add the chart object before setting renderTo:
$.getJSON("val1.json", function (data) {
var chartoptions = data;
if (typeof chartoptions.chart === 'undefined') {
chartoptions.chart = {};
}
chartoptions.chart.renderTo = 'container';
chart = new Highcharts.Chart(chartoptions);
});

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