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

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.

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];

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

CanvasJS - accessing variables - permission denied to access property toString

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

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

how to get tow series data in highchart guage chart

I am ajax calling a php script that outputs two data points
[epoch data, cpu]
I would like to be able to create highchart guage chart and display cpu utilization and as a data lable, I like to display the time that I get from the php call.
function request_cpu_Data() {
$.ajax({
url: 'get_cpu.php',
success: function(data) {
var myObj = JSON.parse(data);
var point = cpu_chart.series[0].points[0];
var point1 = cpu_chart.series[1].points[0];
var newVal=myObj[1];
var newVal1=myObj[0];
point.update(newVal);
point1.update(newVal1);
setTimeout(request_cpu_Data, 10000000);
},
cache: false
});
}
my series options are like this:
series: [{
name: 'CPU',
data: [0]
},{
name: 'Date',
data: []
}
]
I am getting this error:
Uncaught TypeError: Cannot call method 'update' of undefined
Is this how you set up the second series?
var point1 = cpu_chart.series[1].points[0];
Your second series contains no data, so your cpu_chart.series[1].points is an empty array.
You must use setData if data.lenght === 0, like this:
var secondSeries = chart.series[1];
if (secondSeries.data.length === 0) {
secondSeries.setData([newValue]);
} else {
secondSeries.points[0].update(newValue);
}
I hope that will help you.

Categories

Resources