passing json data to chartjs - json

JSON.js
var Jsondata = {
"label1": 0,
"label2": 0,
"label3": 2,
"label4": 0,
"label5": 0
}
var labels = //?? have to get the labels from the Jsondata
var data = //?? have to get the numbers from the Jsondata
and i am using this to make a line graph using chartjs and the code is as follows.
type: 'line',
data: {
labels: labels //["label1","label2","label3","label4", "label5""],
datasets: [{
label:'',
fill: 'false',
data: data //[0, 3, 6, 4, 5,3,2],

You can use the built in Object helpers keys() and values():
var Jsondata = {
"label1": 0,
"label2": 0,
"label3": 2,
"label4": 0,
"label5": 0
}
var labels = Object.keys(Jsondata)
var data = Object.values(Jsondata)
labels:
["label1", "label2", "label3", "label4", "label5"]
data:
[0, 0, 2, 0, 0]

Related

How to create chart using Springboot Json api

i have this service that give back this Json result :
{
"MANNOUBA": 1,
"Medinine": 4,
"Gabes": 5,
"Tunis": 22,
"Beja": 3,
"Kebili": 0,
"Sfax": 11,
"Laundry Making": 6,
"italia": 0,
"Sousse": 6,
"Desk": 1,
"Jendouba": 3,
"Mahdia": 6,
"Ben Arous": 19,
"Zaghouan": 4,
"Gafsa": 0,
"Kairouan": 6,
"Monastir": 18,
"metos": 1,
"Eleonetech": 2,
"Nabeul": 22,
"Mannouba": 9,
"BENAROUS": 8,
"Ariana": 21,
"Bizerte": 3
}
i want to put this data in a Barchart For my angular Project with the names in the X axis and the Numbers in the Y axis
With using Highcharts, you can preprocess your data to the: [name, y] format and use category axis type. Example:
for (let key in data) {
chartData.push([key, data[key]]);
}
Highcharts.chart('container', {
xAxis: {
type: 'category'
},
series: [{
type: 'column',
data: chartData
}]
});
Live demo: http://jsfiddle.net/BlackLabel/cjk3uboh/
Highcharts angular wrapper: https://www.npmjs.com/package/highcharts-angular

Highcharts series data from JSON object

I am new to JSON and mvc so here is my issue. I am currently working on graphs using highcharts. I have a controller which returns a JSON object.
public JsonResult _GetChart_TrendPublicationTypeDetailed_Data(int
yearToDisplay)
{
//Types of publications to be considered
string[] publication_types = new string[] { "article", "book", "book_section", "conference_proceedings" };
//Get the list of outputs with usp authors
var uspPubs = _uspAuthoredPublications();
//List of years for which to display the data
List<int> yearRange = _getListOfYears(yearToDisplay, yearRangeFactor_10);
//Get the data
var data = from eprint_summary in localDB.Summary
where
eprint_summary.Year > (yearToDisplay - yearRangeFactor_10)
&& eprint_summary.Year <= yearToDisplay
&& publication_types.Contains(eprint_summary.TypeCode)
&& uspPubs.Contains(eprint_summary.EprintId)
//&& eprint_summary.refereed == "TRUE" //TODO: Confirm whether we need this filter in our counts
group eprint_summary by new { eprint_summary.Year, eprint_summary.TypeDesc } into typeTrend
orderby typeTrend.Key.Year, typeTrend.Key.TypeDesc
select new
{
Year = typeTrend.Key.Year,
Type = typeTrend.Key.TypeDesc,
Count = typeTrend.Count()
};
//Extract the series data
List<object> countData = new List<object>();
foreach (var item in data.ToList().Select(y => y.Type).Distinct().OrderBy(y => y))
{
List<int> yearlyData = new List<int>();
foreach (var year in yearRange)
{
var rec = data
.Where(y => y.Type == item)
.Where(y => y.Year == year)
.Select(y => y.Count).ToArray();
yearlyData.Add(
rec == null || rec.Length == 0 ? 0 : rec[0]
);
}
countData.Add(
new
{
name = item, //Name of the series
data = yearlyData.ToArray() //Array of data
}
);
}
//Form the json object using the series data and labels
return Json(
new
{
labels = yearRange.ToArray(),
series = countData
},
JsonRequestBehavior.AllowGet
);
}
The above is my JSON in controller.
I have my view as below where I am getting the JSON object but I do not know how to append to my graph as series. How would I convert the JSON object to something that the series accepts.
var seriesData = ' ';
var test = ' ';
function ajaxCall() {
$.ajax({
type: "post",
datatype: "Json",
async: true,
url: '#Url.Action("_GetChart_TrendPublicationTypeDetailed_Data", "ResearchCharts")',
data: { yearToDisplay: '#(DateTime.Now.AddYears(-1).Year.ToString())' },
success: function (data) {
seriesData = data;
test = seriesData.series;
//bindChart(test);
//alert(JSON.stringify(seriesData));
alert(JSON.stringify(test));
},
error: function () {
alert("An error occurred.");
}
});
}
//functions call
ajaxCall();
bindChart(test);
function bindChart(test) {
var test2 = [{ "name": "Book", "data": [14, 17, 9, 10, 6, 19, 6, 8, 0, 4] }, { "name": "Book Chapter", "data": [65, 74, 44, 66, 9, 23, 36, 51, 53, 36] }, { "name": "Conference Proceedings", "data": [15, 17, 27, 30, 28, 54, 35, 43, 50, 35] }, { "name": "Journal Article", "data": [178, 162, 133, 139, 133, 191, 160, 194, 149, 169] }];
$('#chartTrendsPublicationTypeDetailed').highcharts({
chart: {
type: 'line'
},
title: {
text: 'My data'
},
xAxis: {
categories: ['2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016']
},
series: test2//[{ "name": "Book", "data": [14, 17, 9, 10, 6, 19, 6, 8, 0, 4] }, { "name": "Book Chapter", "data": [65, 74, 44, 66, 9, 23, 36, 51, 53, 36] }, { "name": "Conference Proceedings", "data": [15, 17, 27, 30, 28, 54, 35, 43, 50, 35] }, { "name": "Journal Article", "data": [178, 162, 133, 139, 133, 191, 160, 194, 149, 169] }]
});
Please help, just need to somehow pass the data to highcharts.
in the picture, I have added the series manually and it works, but I need to pass in a variable which the series property accepts.
Old Highcharts rendering code:
$('#chartTrendsPublicationRankDetailed').highcharts({
chart: {
type: 'line'
},
title: {
text: 'My data'
},
xAxis: {
categories: labels
},
series: seriesData
});
New Highcharts rendering code. This accepts my JSON objects successfully and renders the graphs.
function bindChartItemType(seriesData, labels) {
var chart = new Highcharts.Chart({
chart: {
renderTo: 'chartTrendsPublicationTypeDetailed',
type: 'line',
height: 500,
width: 500
},
credits: {
enabled: false
},
title: {
text: 'Trend of Publications by Item Type'
},
xAxis: {
categories: labels,
title: {
text: '<b>Year</b>'
}
},
yAxis: {
min:0,
title: {
text: '<b># of publications</b>'
}
},
series: seriesData
});
}
Feel free to add anything you like in the comments.
Regards
Shafraz Buksh

Data aggregation in c3js

Is there an option to aggregate the data in C3 charts? When the JSON contains multiple data elements with the same category, data is plotted as multiple points in the charts, where as it should be aggregated and shown as a single point in the chart.
Attached are the C3 charts and expected chart format.
In the example: "name 1" show a single point at 300 as upload, where as ion C3 it show one point at 200 and the other at 100 for the same.
Code Used:
var chart = c3.generate({
bindto:'#png-container',
data: {
json: [
{name: 'name1', upload: 200, download: 200, total: 400},
{name: 'name1', upload: 100, download: 300, total: 400},
{name: 'name2', upload: 300, download: 200, total: 500},
{name: 'name3', upload: 400, download: 100, total: 500},
],
keys: {
x: 'name', // it's possible to specify 'x' when category axis
value: ['upload', 'download'],
},
groups: [
['name']
]
},
axis: {
x: {
type: 'category'
}
}
});
Output of the above code:
Expected Output:
Not built into c3 as far as i'm aware. You can use d3's nest operator to aggregate the json data before passing it to c3 though.
var json = [
{name: 'name1', upload: 200, download: 200, total: 400},
{name: 'name1', upload: 100, download: 300, total: 400},
{name: 'name2', upload: 300, download: 200, total: 500},
{name: 'name3', upload: 400, download: 100, total: 500},
];
var agg = function (json, nestField) {
var nested_data = d3.nest()
.key(function(d) { return d[nestField]; })
.rollup(function(leaves) {
// Work out the fields we're not nesting by
var keys = d3.merge (leaves.map (function(leaf) { return d3.keys(leaf); }));
var keySet = d3.set(keys);
keySet.remove (nestField);
var dataFields = keySet.values();
// total these fields up
// console.log(leaves, dataFields); // just for testing
var obj = {};
dataFields.forEach (function (dfield) {
obj[dfield] = d3.sum(leaves, function(d) {return d[dfield];});
});
return obj;
})
.entries(json);
// return to original json format
var final_data = nested_data.map (function(nestd) {
nestd.values[nestField] = nestd.key;
return nestd.values;
});
return final_data;
};
var chart = c3.generate({
bindto:'#png-container',
data: {
json: agg(json, "name"),
keys: {
x: 'name', // it's possible to specify 'x' when category axis
value: ['upload', 'download'],
},
groups: [
['name']
]
},
axis: {
x: {
type: 'category'
}
}
});
https://jsfiddle.net/8uofn7pL/2/
whoops, linked to the wrong fiddle there

Highcharts stacked bar data from CSV

I'm trying to implement a stacked bar chart with data coming from a CSV.
I need to update series: with the data from the CSV file which contains, for example "John,10,5,3,4,1".
Help please!
$(function () {
$('#container').highcharts({
chart: {
type: 'bar'
},
title: {
text: 'Stacked bar chart'
},
xAxis: {
categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
},
yAxis: {
min: 0,
title: {
text: 'Total fruit consumption'
}
},
legend: {
reversed: true
},
plotOptions: {
series: {
stacking: 'normal'
}
},
series: [{
name: 'John',
data: [5, 3, 4, 7, 2]
}, {
name: 'Jane',
data: [2, 2, 3, 2, 1]
}, {
name: 'Joe',
data: [3, 4, 4, 2, 5]
}]
});
});
UPDT
I finally got it working, but still there's a problem. The bars are inverted and I need them to be exactly in the same order as in the CSV file.
Here's my parser:
$.get('chart.csv', function(data) {
var lines=data.split('\n');
$.each(lines, function(lineNo, line) {
var items = line.split(',');
var series = {
data: []
};
$.each(items, function(itemNo, item) {
if (itemNo == 0) {
series.name = item;
} else {
series.data.push(parseFloat(item));
}
});
options.series.push(series);
});
var chart = new Highcharts.Chart(options);
The contents of the CSV file:
Disconnection,30,30
Site Care,12,12
Documentation,35,35
Lining,22,22
Connection,70,52
I need the stacked bars in the same order as in the legend:
http://i.stack.imgur.com/6EkHg.png
You could try to custom setting the series indices before you render the chart to fix the inversion of the bars.
Something like this might do the trick:
for (var i = 0; i < options.series.length; i++) {
options.series[i].index = options.series.length - 1 - i;
options.series[i].legendIndex = i;
}

json date format to Highcharts date format

Could please someone guide me how to get such json object datetime
{
value="01/01/2013 08:00",
key=5.5
}
to javascript (to use in Highcharts) datetime acceptable format
[Date.UTC(2013, 0, 1,08,00), 5.5].
UPDATE
Here is what I'm trying to do:
var chart;
$(document).ready(function () {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
zoomType: 'x'
},
yAxis: {
type: 'double',
min: 0
},
xAxis: {
type: 'datetime',
labels: {
formatter: function () {
return Highcharts.dateFormat('%a %d %b %H:%M', this.value);
},
dateTimeLabelFormats: {
minute: '%H:%M',
hour: '%H:%M',
day: '%e. %b',
week: '%e. %b',
month: '%b \'%y',
year: '%Y'
}
}
},
series: [{
name: 'MyData1',
data: []
}, {
name: 'MyData2',
data: []
}]
});
chart.series[0].setData([
[Date.UTC(2013, 0, 1, 08, 00), 4.4],
[Date.UTC(2013, 0, 1, 12, 00), 6.0],
[Date.UTC(2013, 0, 1, 17, 00), 7.7],
[Date.UTC(2013, 0, 1, 22, 00), 5.8]
]);
chart.series[1].setData([
[Date.UTC(2013, 0, 1, 08, 30), 0.4],
[Date.UTC(2013, 0, 1, 10, 00), 0.0],
[Date.UTC(2013, 0, 1, 16, 00), 0.7],
[Date.UTC(2013, 0, 1, 20, 00), 0.8]
]);
});
here is it in jsFiddle.
var datatype1=[];
var datatype2= [];
for(index in userReadingsJsonCollection.items){
if(userReadingsJsonCollection.items[index].ReadingsData.Reading_Type==type1){
datatype1.push(
[Date.parse(userReadingsJsonCollection.items[index].ReadingsData.Rec_DateTime),
userReadingsJsonCollection.items[index].ReadingsData.Reading]
);
}
if(userReadingsJsonCollection.items[index].ReadingsData.Reading_Type==type2){
datatype2.push(
[userReadingsJsonCollection.items[index].ReadingsData.Rec_DateTime,
userReadingsJsonCollection.items[index].ReadingsData.Reading]
);
}
}
The result I get is [[1357027200000,5.5]] and this works great.
If your time is already UTC then it's as simple as:
Date.parse("01/01/2013 08:00")
EDITS
Assuming your data comes back as valid JSON:
var jsonObj = {value:"01/01/2013 08:00", key:5.5};
var seriesOneData = [];
seriesOneData.push([Date.parse(jsonObj.value),jsonObj.key]);