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/
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'm beginner...
I'm using kendo-grid with Jquery.
I want to get current sorted field in kendo-gird.
I found this.
console.log(grid.dataSource._sort[0].dir);
console.log(grid.dataSource._sort[0].field);
Can I find alternative way?
this is my code.
var dataSource = new kendo.data.DataSource({
transport : {
read : {
type : 'post',
dataType : 'json',
contentType : 'application/json;charset=UTF-8',
url : cst.contextPath() + "/watcher/kendoPagination_statsErrorHistoryRetrieveQry.htm",
data : param
},
parameterMap: function (data, opperation) {
return JSON.stringify(data);
}
},
schema : {
data : function(data) {
return data;
},
total : function(response) {
return response.length > 0 ? response[0].TOTAL_COUNT : 0;
}
},
pageSize : cst.countPerPage(),
serverPaging : true,
serverSorting : true
});
var columns = kendoGridColumns();
$("#grid")
.kendoGrid({
dataSource : dataSource,
sortable : {
mode : 'multiple',
allowUnsort : true
},
columns : columns.error()
selectable : 'row',
scrollable : true,
resizable : true,
}));
How can I get current sorted field name?
Avoid using private fields. The DataSource sort method is the official way to get the current sort state:
http://docs.telerik.com/kendo-ui/api/javascript/data/datasource#methods-sort
var dataSource = new kendo.data.DataSource({
data: [
{ name: "Jane Doe", age: 30 },
{ name: "John Doe", age: 33 }
],
sort: { field: "age", dir: "desc" }
});
var sort = dataSource.sort();
console.log(sort.length); // displays "1"
console.log(sort[0].field); // displays "age"
I have json data in the following format :
[{
"label" : "A Label" ,
"value" : -29.765957771107
} ,
{
"label" : "B Label" ,
"value" : 0
} ,
{
"label" : "C Label" ,
"value" : 32.807804682612
} ,
{
"label" : "D Label" ,
"value" : 196.45946739256
}]
I want to create a bar chart in NVD3 where x coordinates will be label and the y coordinates will be the value. So how can I achieve it. I have gone through many examples where the JSON data was used is a different format but my data is as shown above.
EDITED CODE:
Here is the js code through which I am trying to create a chart in NVD3 .
d3.json("http://localhost:8080/api/study", function(data) {
nv.addGraph(function() {
var chart = nv.models.multiBarHorizontalChart().x(function(d) {
return d.label;
}).y(function(d) {
return d.value;
}).margin({
top : 30,
right : 20,
bottom : 50,
left : 175
}).showValues(true)//Show bar value next to each bar.
.tooltips(true)//Show tooltips on hover.
//.transitionDuration(350)
.showControls(true);
//Allow user to switch between "Grouped" and "Stacked" mode.
chart.yAxis.tickFormat(d3.format(',.2f'));
d3.select('#chart11 svg').datum(data).call(chart);
nv.utils.windowResize(chart.update);
return chart;
});
});
Most charts in nvd3.js have the following data sceleton:
[
{
key: "<Series name>",
color: "<CSS color>",
values: [
{x: 0, y: 10},
{x: 1, y: 20},
{x: 2, y: 30}
....
]
},
{
key: "<Series name>"
...
}
]
In your case the following format will be valid:
[
{
key: "Series 1",
values: [
{
"label" : "A Label" ,
"value" : -29.765957771107
} ,
{
"label" : "B Label" ,
"value" : 0
} ,
{
"label" : "C Label" ,
"value" : 32.807804682612
} ,
{
"label" : "D Label" ,
"value" : 196.45946739256
}
]
}
]
You will need to specify axis properties accessors:
var chart = nv.models.discreteBarChart()
.x(function(d) { return d.label })
.y(function(d) { return d.value })
I'm adding and removing data to a Kendo dataSource. I wish to save it localStorage, and be able to read it again from localStorage.
Here I've attempted to use jStorage for the saving and loading of data.
How it's loaded:
if ($.jStorage.get('favoritter') != null) {
var datakilde_favoritter = $.jStorage.get('favoritter');
} else {
var data = [
{id: 5, name: "LINK ONE", url: "http://www.linkone.com" }
];
var datakilde_favoritter = new kendo.data.DataSource({
data: data,
sort: { field: "name", dir: "asc" }
});
}
How it's saved:
$.jStorage.set('favoritter', datakilde_favoritter);
Define your DataSource as:
var ds = new kendo.data.DataSource({
transport: {
read : function (op) {
var data = $.jStorage.get('favoritter');
if (!data) {
data = [
{id: 5, name: "LINK ONE", url: "http://www.linkone.com" }
];
}
op.success(data);
},
update : function (op) {
$.jStorage.set("favoritter", ds.data());
op.success(op.data);
},
destroy: function (op) {
console.log("destroy", ds.data());
$.jStorage.set("favoritter", ds.data());
op.success(op.data);
},
create : function (op) {
$.jStorage.set("favoritter", ds.data());
op.success(op.data);
}
},
sort : { field: "name", dir: "asc" },
pageSize : 10,
schema : {
model: {
id : "id",
fields: {
id : { type: 'number' },
name: { type: 'string' }
}
}
}
});
You might consider removing create and destroy if not needed.
And your grid would be something like:
var grid = $("#grid").kendoGrid({
dataSource: ds,
editable : "popup",
pageable : true,
toolbar : ["create"],
columns : [
{ command: ["edit", "destroy"], width: 100 },
{ field: "id", width: 90, title: "#" },
{ field: "name", width: 90, title: "URL Name" }
]
}).data("kendoGrid");
Basically when updating you need to invoke op.success with the data returned from the server. In your case since it is the browser itself, you don't need just to return the original data.
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.