I have been encountering issues for the past few days with ajaxing in some sample json data from an external file to populate a pie chart using the Highcharts library.
Here is my sample JSON data in file: data.json
[
["Apples", 43.0],
["Pears", 57.0]
]
Here is my implementation of highcharts and my AJAX call:
(I have omitted unrelated code)
<script type="text/javascript">
$(function() {
var options = {
chart: {
renderTo: 'Chart',
defaultSeriesType: 'pie'
},
title: {
text:'Fruits'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: '#000000',
}
}
},
series: [{
type: 'pie',
name: 'Fruits',
data: []
}]
};
$.getJSON('data.json', function(json) {
options.series.push(json);
var chart = new Highcharts.Chart(options);
}).error(function() {console.log('error');});
});
</script>
Basically, I want to pass in the JSON, into options.series[].data[]. When proceed with
options.series.push(json);
I get:
[Object, Array[2]] // where the Object contains .name and .type and the Array[2] is my data
I'm pretty sure I need this:
[Object] // which contains .data , .name, .type
I was actually able to solve my problem by structuring my JSON like so:
[
{
"type" : "pie",
"name" : "Fruits",
"data" : [
[
"Apple",
43.0
],
[
"Pear",
"57.0"
]
]
}
]
and instead of doing an array push,
I set the series parameter to the JSON like this:
$.getJSON("data.json", function(json)) {
options.series = json;
var chart = new Highcharts.chart(options);
}
Just in case anyone else runs across this like I did. I solved the same problem with series.data.push as series is an array also, highcharts would not have known we were actually trying to push the value into data instead.
Related
I would like to implement a simple line graph with ajax in which only two points
x will be the hours and y will be the count of calls.
CODE :
<script>
function getData() {
$.ajax({
type:'POST',
url: "http://localhost/demo_chart/test.php",
dataType: 'JSON',
success: function(response_data) {
new_data = $.map(response_data, function(i){
return {x: i['date'],y: i['count']};
});
$('#container').highcharts({
chart: {
renderTo: 'container',
type: 'line'
},
title: {
text: 'Count vs. Time'
},
xAxis: {
title: {
text: 'Time'
},
type: 'Time',
},
yAxis: {
title: {
text: 'Count'
}
},
series: [{
name: 'Test',
data: new_data
}]
});
}
})
}
$(document).ready(function () {
getData();
})
</script>
Output of http://localhost/demo_chart/test.php is same as below :
{"date":["13:00:00","13:00:01","13:00:02","13:00:03","13:00:04"],"count":["1","2","3","4","2"]}
But still graph is not generating. So i would like to know what is the problem here.
Anyone like to share some hint which can resolve this problem ?
Expected output is :
X- axis : show all date
Y-axis : show count
You need to correct your mapping function, for example:
var response = {
"date": ["13:00:00", "13:00:01", "13:00:02", "13:00:03", "13:00:04"],
"count": ["1", "2", "3", "4", "2"]
};
new_data = $.map(response.date, function(el, index) {
return {
name: el,
y: parseInt(response['count'][index])
};
});
Additionally, with that data structure, I recommend you to use category axis type.
xAxis: {
...,
type: 'category'
}
Live demo: http://jsfiddle.net/BlackLabel/ptx6fy2q/
API Reference: https://api.highcharts.com/highcharts/xAxis.type
I use jquery.dataTables.min.js for Data table..
then i try to use highcharts. but when i put highcharts code in document ready function then dataTable lost his functionality.. such as search box, scroll, design.
$(function() {
/*For Highcharts*/
var chart1 = new Highcharts.Chart({
chart: {
renderTo: 'my_chart',
type: 'line'
},
title: {
text: 'Monthly National Trend of SOMA-JECT Administration'
},
xAxis: {
categories: ['January', 'February', 'March']
},
yAxis: {
title: {
text: 'No. of SOMA-JECT Administration'
}
},
series: [{
name: 'Soma-JECT',
data: [1, 0, 4]
}, {
name: 'Sayana PRESS',
data: [5, 7, 3]
}]
});
/*For Data Table*/
$('#example').DataTable({
scrollX: true
});
});
Try to change order of scripts. highcharts scripts move to bottom of dataTable scripts then may be everything is OK.
I am using Telerik Kendo Grid; it wouldn't allow to use the sortable functionality of the table when my datasource (array) looks as below:
var myArray = [
{ Destination = { Country: "United Kingdom", AircraftTypeCount: 9 }, Origin= [ {Country: "United States", Code: "JFK"} ] },
{ Destination = { Country: "Egypt", AircraftTypeCount: 5 }, Origin= [ {Country: "Qatar", Code: "QR"} ] }]
It renders the country column fine, but when I click on the column the sorting doesn't occur. Below is my Kendo Grid (using AngularJS):
$("#myKendoTable").kendoGrid({
dataSource: {
data: myArray
},
sortable: {
mode: "multiple",
allowUnsort: true
},
columns: [
{
field: "Country",
title: "Country",
width: 300,
template: function (item) {
return item["Destination"].Country;
}
}
]
});
I've just sorted this out. It seems that Kendo's sorting functionality recognises basic array structure, so I had retrieve all Destinations from myArray into a separate array, and use that new array as the datasource.
I used the following method to do so (using underscoreJS):
function getDestinationsData(airlineRoutes)
{
return _.map(AirlineDestinationRoutes, function (airlineRoutes) { return airlineRoutes.Destination });
}
I am trying to create a chart in c3.js and my data is coming from an external API. I want to get the data and the keys from the json data so that I can plot the values on the chart. I have added the external api format and the js code below.
JSON DATA:
[{
"label" : "A Label" ,
"value" : -29.765957771107
} ,
{
"label" : "B Label" ,
"value" : 0
} ,
{
"label" : "C Label" ,
"value" : 32.807804682612
} ,
{
"label" : "D Label" ,
"value" : 196.45946739256
}]
JS Code:
d3.json("http://localhost:8080/api/study", function(data) {
var chart = c3.generate({
bindto : '#chartContainer',
data : {
columns : ['label']
},
keys: {
x: 'label',
value: ['value']
}
});
});
Thank You
Pre-process the API data into the format that C3 requires. It should be straightforward:
var convertedData = [];
apiData.forEach(function(item){
convertedData.push([item.label, item.value]);
});
Here's an example: http://jsfiddle.net/jrdsxvys/2/
EDIT:
If you're wanting to use the JSON data option with the value array, then it would be something like this, where you set the json property, and the keys object:
var chart = c3.generate({
data: {
json: data,
keys: {
x: 'label',
value: ["value"]
},
type: 'bar'
},
axis: {
x: {
type: 'category'
}
},
legend: {
show:false
}
});
Fiddle: http://jsfiddle.net/jrdsxvys/4/
I am trying to achieve a behaviour as below:
But my chart is shown as below. It has only one record in the json array
Even if there is no data for some days on a week, i need to show the weekdays as in the first image.
Fiddle here
$("#kk").kendoChart({
dataSource: {
data:_data
},
seriesColors: ["Orange"],
seriesDefaults: {
type: "column",
gap: .5,
overlay: {
gradient: "none"
}
},
series: [{
name: "weight",
field: "weight",
categoryField: "createddate",
aggregate: "avg",
}],
categoryAxis: {
type: "date",
baseUnit: "weeks",
labels: {
rotation: -45,
dateFormats: {
weeks: "ddd"
}
},
majorGridLines: {
visible: false
},
majorTicks: {
visible: false
}
}
});
So all you need to do is append end points to your array of data. You can do this in your controller that returns data or later with JavaScript (which will cause you to redraw the chart unless you catch the data before you place it in the chart.)
You will need to make an array of Json objects like the rest of your data. It may look somthing like this. startDate and endDate being your chosen range.
function endPoints(){
return [{createddate:startDate,weight:0},{createddate:endDate,weight:0}];
}
You can append these data points with something like this.
function addDataToChart(data) {
var ds = $('#kk').data('kendoChart').dataSource;
ds.data($.merge(data, endPoints()));
//You can use ds.data() if you want to use the data that is already in the chart
}
In my own Dashboard project I would get the data with my own Ajax calls and append endPoints before it was placed in the chart. The full ajax function could look like this.
$.ajax({
url:'URLtoReturnData'
dataType:'json',
success:function(data){addDataToChart(data);},
error:function(e){errorHandler(e);}
});
I hope this helps.
This a workaround to get dates with no values to be displayed. The workaround is to have weight as 0.000000000000000001 for dates that has got no weight values against it. Also i have updated the category baseunit to days and added some sample data for you so that you can have a look at it how it appears. What you can do is put 0.000000000000000001 for dates that have 0 value against it when you are returning the JSON Markup. Code as below:
#*Sample Data:*#
var _data=[{"weight":149.91,"createddate":"8/1/2014"},
{"weight":0.000000000000000001,"createddate":"8/2/2014"},
{"weight":200,"createddate":"8/3/2014"},
{"weight":0.000000000000000001,"createddate":"8/4/2014"}]
$("#kk").kendoChart({
dataSource: {
data:_data
},
seriesColors: ["Red"],
seriesDefaults: {
type: "column",
},
series: [{
name: "weight",
field: "weight",
categoryField: "createddate",
}],
categoryAxis: {
type: "date",
baseUnit: "days",
labels: {
rotation: -45,
dateFormats: {
days: "ddd"
}
},
}
});
Please have a look at this JSFiddle for the same to see output