I'm making c3js chart that looks like:
var chart = c3.generate({
bindto: '#chart',
data: {
columns: []
}
});
Then I'm trying to use load function from it's api:
var data = [["Name", "15", "30", "45"], ["x", "1", "2", "3"]];
function update_graph(arg) {
var tmp = arg[0][1];
chart.load({
xs: {
tmp : arg[1][0] //binding data to x here and getting an error
},
columns: [
arg[0],
arg[1]
],
});
}
update_graph(data);
And I'm getting: Uncaught Error: x is not defined for id = "Name".
If I set in xs section: Name : arg[1][0] - it does work. But then I will not be able to draw different lines from different arrays with this function. What am I doing wrong ? Thank you.
Working code to make setting key/value to be generic from 'arg' 2D array:- jsFiddle
Solution is to construct the xs object first like:-
var xs = {};
xs[arg[0][0]] = arg[1][0];
xs[arg[2][0]] = arg[3][0];
and then use xs object in the chart.load function like:-
chart.load({
xs: xs,
columns: [
arg[0],
arg[1],
arg[2],
arg[3],
],
});
Note that key in xs object is not hardcoded to 'Name' or 'Age' string.
Hope this works for you.
Following example is working fine, with multiple lines defined in different arrays.- jsFiddle
var chart = c3.generate({
bindto: '#chart',
data: {
columns: []
}
});
var data = [["Name", "15", "30", "45"], ["x", "1", "2", "3"], ["Age", "45", "38", "25"], ["y", "1", "2", "4"]];
function update_graph(arg) {
var tmp = arg[0][1];
chart.load({
xs: {
Name : arg[1][0],
Age : arg[3][0] //binding data to x here and getting an error
},
columns: [
arg[0],
arg[1],
arg[2],
arg[3],
],
});
}
update_graph(data);
Not sure what the issue is, which version of c3js library are you using?
Please refer to the c3js example:- c3js Example
$scope.barchart = function(data,id,chtype,keydata)
{
var xs1 = {};
var key1 = $scope.obj.key;
var data1 = $scope.obj.data;
xs1[key1] = data1;
var id = c3.generate({
bindto : '#'+id,
data: {
xs:xs1,
columns: data,
type: 'scatter',
},
});
}
Related
Since i am not familiar with C3.js library, i am bit confuse when i tried to split the Array data.
For instant i have some array value from a json.
var jsondata=[[123],[45],[56],[22]];
var jsondataName=[["apple"],["orange"],["banana"],["pear"]];
I tried to pass the first array jsondata into the chart but these values go into the same column which is not something i would like to see.
I want these array value become independent data and push the name into it
Please see the demo i made :
http://jsfiddle.net/q8h39/92/
And the result i want should looks like
Update the json data format :
"Name": apple,
"data": {
"value": 1434,
}
"Name": banana,
"data": {
"value": 342,
}
}
}
You can set the JSON object to data.json and then set data.keys.value to an array of values in that JSON:
var jsondata = [{
"Name": "apple",
"data": {
"value": 1434,
},
}, {
"Name": "banana",
"data": {
"value": 342,
}
}];
var chart = c3.generate({
data: {
json: jsondata,
keys: {
value: [
"name", "data.value"
]
},
type: "scatter"
//hide: true
}
});
http://jsfiddle.net/aendrew/mz9ccbrc/
n.b., You need C3 v0.4.11 for this (the dot syntax for keys.value was just added), and your JSON object needs to be an array (currently it's not valid).
If you want to convert the two arrays from your initial question to that format of JSON, try this:
d3.zip(jsondataName, jsondata)
.map((d) => Object({name: d[0][0], data: { value: d[1][0] } }));
I decided it would be a fun project to see if i could take data from Google Analytics and display that in a custom dashboard, and hopefully learn a thing or two about using json, and javascript.
after a lot of debugging i now managed to pull the data from the Google Analytics server with their php api, and save the output into data.json on the server.
below the data.json, it's valid as per JSONLint.com:
{
"0": {
"date": "20160113",
"pageviews": "46",
"sessions": "21"
},
"1": {
"date": "20160114",
"pageviews": "66",
"sessions": "18"
},
"2": {
"date": "20160112",
"pageviews": "50",
"sessions": "14"
},
"3": {
"date": "20160116",
"pageviews": "19",
"sessions": "14"
},
"4": {
"date": "20160117",
"pageviews": "23",
"sessions": "14"
},
"5": {
"date": "20160115",
"pageviews": "38",
"sessions": "11"
},
"6": {
"date": "20160118",
"pageviews": "35",
"sessions": "9"
},
"7": {
"date": "20160119",
"pageviews": "15",
"sessions": "7"
}
}
Now i've tried to use the data from data.json and feed it into chartist's labels/series in order to draw a graph.
var labelArray = [];
var seriesArray = [];
var labelOutput = [];
$.getJSON("data.json", function(json) {
//var jsonObj = JSON.parse(json);
for (var i in json){
labelArray.push(json[i].date);
};
for (var i in json){
seriesArray.push(json[i].sessions);
};
// var myData = {
// labels:
// }
// labelOutput = labelArray.join(',')
// seriesOutput = serieArray.join(',')
console.log(labelArray);
console.log(seriesArray);
// this will show the info it in firebug console
});
new Chartist.Line('.ct-chart', {
labels: [labelArray],
series: [[seriesArray]]
});
However I'm currently out of ideas why this would not work, the labels on X and Y axis are correctly shown, but no graph shows up.
I've tried using .join to see if that makes a difference, but using labelOutput instead of labelArray also doesn't change anything.
In the console the array that is being fed into chartist seems all right to me, if I copy paste it from the console into the script everything works.
Current output for labelArray and seriesArray:
labelArray
Array [ "20160113", "20160114", "20160112", "20160116", "20160117", "20160115", "20160118", "20160119" ]
seriesArray
Array [ "21", "18", "14", "14", "14", "11", "9", "7" ]
Anyone knows why chartist.js does manage to add the correct labels along the axes but fails to read the same data and draw the chart?
Although the answer by #mnutsch works, there is an easier way to add dynamic content into the chart.
You can simply add the arrays directly as parameters, which I think is what the OP was trying to do.
response object would be the ajax data
var seriesVals = [];
var labelsVals = [];
for (var i = 0; i < response.length; i++) {
seriesVals.push(response[i].total);
labelsVals.push(response[i].response_code);
}
var pieData = {
series: seriesVals,
labels: labelsVals
};
In case anyone comes across this later, you can also do it like this:
//Create javascript arrays with the values and labels, replace this with code to read from the database/API/etc.
var array_1_values = [100, 120, 180, 200, 90]; //these are the values of the first line
var array_2_values = [20, 35, 65, 125, 245]; //these are the values of the second line
var array_labels = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']; //these are the labels that will appear at the bottom of the chart
//create a prototype multi-dimensional array
var data_chart1 = {
labels: [],
series: [
[],
[]
]
};
//populate the multi-dimensional array
for (var i = 0; i < array_1_values.length; i += 1)
{
data_chart1.series[0].push(array_1_values[i])
data_chart1.series[1].push(array_2_values[i])
data_chart1.labels.push(array_labels[i])
}
//set the size of chart 1
var options_chart1 = {
width: '300px',
height: '200px'
};
//create chart 1
new Chartist.Line('#chart1', data_chart1, options_chart1);
In case anyone else stumbles upon the problem, below is what I came up with to get it to work.
After another day of trail and error i managed to pinpoint the problem.
The problem was:
In the original situation I tried to use a plain array as input for both labels and series. However, Chartist requires objects to render the labels/series as well as the graph.
The below works for me pulling the data from the data.json, adding it to an object and provide it to chartist.
var labelArray = {};
var seriesArray = {};
var labelOutput = [];
var Output
// $.getJSON("data.json", function(json) {
$.ajax({
url: 'data.json',
async: false,
dataType: 'text',
success: function(json) {
labelArray = JSON.parse(json);
data = {
labels:
[
labelArray[0].date,
labelArray[1].date,
labelArray[2].date,
labelArray[3].date,
labelArray[4].date,
labelArray[5].date,
labelArray[6].date
],
series: [[
labelArray[0].sessions,
labelArray[1].sessions,
labelArray[2].sessions,
labelArray[3].sessions,
labelArray[4].sessions,
labelArray[5].sessions,
labelArray[6].sessions
]]
}
}
});
new Chartist.Line('.ct-chart', data);
Decided to go with $.ajax to get the json file rather than getJSON as this allows me to disable asynchronous loading, ensuring the data is available when the graph is drawn.
Also, it is possible to set the dataType to Json rather than text, but this gives error in the JSON.parse line. Assuming that is because it tries to parse json as json, and fails to do so. But this is the only way i managed to get it to work, and add the json to an object.
Most likely the whole labelArray[0].date, labelArray[1].date is rather inefficient and should be improved but it works for now.
I have to create a column chart in my project using Highchart. I am using $.ajax to populate this data. My current JSON data is like this :
[{
"city": "Tokyo",
"totalA": "10",
"totalB": "15"
},
{
"city": "Seoul",
"totalA": "20",
"totalB": "27"
},
{
"city": "New York",
"totalA": "29",
"totalB": "50"
}]
How to resulting JSON string look like this:
[{
"name": "city",
"data": ["Tokyo", "Seoul", "New York"]
}, {
"name": "totalA",
"data": [10, 20, 29]
}, {
"name": "totalB",
"data": [15, 27, 50]
}]
Thank you.
Assuming all the elements look the same (they all have the same fields): Live Example
// src is the source array
// Get the fields from the first element
var fields = Object.keys(src[0]);
// Map each key to...
var result = fields.map(function(field) {
// Grab data from the original source array
var data = src.reduce(function(result, el) {
// And create an array of data
return result.concat(el[field]);
}, []);
// Format it like you want
return {name: field, data: data};
});
console.log(result);
If they aren't, the code is slightly more complicated: Live Example
// Work out the fields by iterating all of the elements
// and adding the keys that weren't found yet to an array
var fields = src.reduce(function (fields, current) {
return fields.concat(Object.keys(current).filter(function (key) {
return fields.indexOf(key) === -1;
}));
}, []);
var result = fields.map(function (field) {
// Need another step here, filter out the elements
// which don't have the field we care about
var data = src.filter(function (el) {
return !!el[field];
})
// Then continue like in the example above.
.reduce(function (result, el) {
return result.concat(el[field]);
}, []);
return {
name: field,
data: data
};
});
console.log(result);
I would like to cache data from remote database locally to use it in my javascript application. I do not need any excesses such as SQL requests to local data, so I decide just to store database records in array of objects in the following way:
<script type="text/javascript">
var json0 = '{"1" : {"fname": "fname1", "sname": "sname1"}, "2" : {"fname": "fname2", "sname": "sname2"}}';
var json1 = '{"2" : {"data": "11/05/2014", "time": "11:30:18", "person": "data0[1]"}, "6" : {"data": "24/06/2014", "time": "16:11:05", "person": "data0[2]"}, "8" : {"data": "11/10/2014", "time": "12:15:27", "person": "data0[1]"}}';
var data0 = JSON.parse(json0);
var data1 = JSON.parse(json1, function (k, v) {
try {
return eval(v);
} catch (e) {
return v;
}
});
console.log(data1);
</script>
The question is about the memory usage. If the objects in array data1 will store the reference to the objects from data0 in the property "person" or they will store the copy of these objects?
as reducing version of your example shows, data0 will be stored by reference.
var tt = {f1: 'aa', f2: 'bb'}
var rr = eval('tt');
console.log(rr.f1); // 'aa'
rr.f1 = 'cc';
console.log(tt.f1); // 'cc'
But using eval(..) is bad way: Why is using the JavaScript eval function a bad idea? . Use local storage instead as jeff said.
Hello i have problem to load data in flotchart.js
here's the original code that works
var pageviews = [
[1,2],
[2, 3]
];
var visitors = [
[1, 3],
[2, 2]
];
var plot = $.plot($("#site_statistics"), [{
data: pageviews,
label: "Unique Visits"
}, {
data: visitors,
label: "Page Views"
}]);
but when i change the data that i load from json it doesn't work.
here's the data json on load_statistik_bidang.php:
[{"data":[["1",12],["1",11],["3",10],["14",9]],"label":"EMSA"},{"data":[["1",12],["4",9]],"label":"BSSA"},{"data":[["1",2],["1",10]],"label":"OSSAC"}]
if i copy the json in manual it's works but when im using function to load the data it doesnt work .
code that i load the json is like this :
function loadMyData(){
$.ajax({
url:"load_statistik_bidang.php",
dataType: "json",
method:"get",
success: function(data){
tampung = data;
console.log(data.EMSA);
}
});
}
var plot = $.plot($("#site_statistics"), tampung);
any ideas for this? thanks
Your JSON is broken/invalid. You're not closing your first data array.
Should look like this:
[{
"label": "EMSA",
"data": [
[
"1",
12
],
[
"1",
11
]
] // <-- you forgot this
},
{
"label": "BSSA",
"data": [
[
"1",
12
],
[
"4",
9
]
]
}
]
You can use this site to validate it in the future:
http://jsonlint.com/