Two line chart from JSON on c3.js - javascript

i've got a JSON that store multiple value like this,
[
{"Description":"bankname1", "Month":"April", "Amount":"1700"},
{"Description":"bankname1", "Month":"June", "Amount":"1300"},
{"Description":"bankname1", "Month":"March", "Amount":"1500"},
{"Description":"bankname2", "Month":"March", "Amount":"100"},
{"Description":"bankname2", "Month":"April", "Amount":"1200"},
]
Into this JSON I've 12 Month for each Bankname (JSON can have multiple bank name).
I would like to show a line-bar for each bankname and on x axis show Month name.
At this moment I can see only one line chart with value of bank mixed on name line.
this is my code:
var chart = c3.generate({
bindto: '#c3_incassi',
data: {
json: data,
keys: {
x: 'MONTH',
value: ['AMOUNT']
},
type: 'line'
},
axis: {
x: {
type: 'category',
categories: ['GENNAIO', 'FEBBRAIO', 'MARZO', 'APRILE', 'MAGGIO', 'GIUGNO', 'LUGLIO', 'AGOSTO', 'SETTEMBRE', 'OTTOBRE', 'NOVEMBRE', 'DICEMBRE'],
}
}
});
How can I solve this problem?
Many thanks
Bye
Francesco

You need to get your json data into the correct format, as already commented by Abhas. The correct json format for c3.js line chart with multiple lines looks as follows:
{"bankname1":[1700,1300,1500,1100,1400,1800,2000,2100,1900,1100,1250,1050],"bankname2":[100,1200,300,1100,400,700,350,200,1200,1400,1050,900]}
The json string would contain the "bankname1" followed by 12 numeric values, one for each month, then "bankname2" followed by the 12 numeric values etc.
If you are using php at server-side, you can echo your json data, let's call it "dataset", into c3.js by:
var dataset = <?php echo $dataset; ?>;
data: {
json: dataset
},
I am doing it the excact same way and it works. The axis labels you can set up as in your code:
axis: {
x: {
type: 'category',
categories: ['GENNAIO', 'FEBBRAIO', 'MARZO', 'APRILE', 'MAGGIO', 'GIUGNO', 'LUGLIO', 'AGOSTO', 'SETTEMBRE', 'OTTOBRE', 'NOVEMBRE', 'DICEMBRE'],
}
}

Related

How to show categorized Highcharts Chart using csv file

I'm trying to show a Chart with Highcharts, using javascript.
I've read the csv file using Highcharts modules/data.js and the Chart is showing without problems inside my container.
mychart = Highcharts.chart('container', {
chart: {
type: 'scatter',
zoomType: 'xy'
},
data: {
csv: csv,
startColumn:0,
endColumn:2
},
title: {
text: 'DATA'
},
xAxis: {
title: {
text: 'X'
},
},
yAxis: {
title: {
text: 'Y'
}
}
});
Basically the csv have 3 columns, with commas separating attributes and break lines for each row.
x, y, category
data1, data2, data3
data1, data2, data3
data1, data2, data3
data1, data2, data3
data1, data2, data3
...
The first and the seconds columns are the points coordinates and the third is the category. I want to display points based on one of the categories in the third row.
I don't know how to show all x & y points categorized by category column.
You can think of a category as a series in Highcharts. So you need to create an array like this
series: [{
name: 'Series ' + categoryNumber,
data: [] // array with x and y coordinates
}, {
name: ''
data: []
}]
Then you can parse your csv file, it would be easier without data module.
var rows = csv.split('\n');
var series = [];
rows.forEach(row => {
var cells = row.split(',').map(Number);
var serie = series[cells[2]];
if (!serie) {
serie = series[cells[2]] = {data: []};
}
serie.data.push([cells[0], cells[1]]);
})
Highcharts.chart('container', {
chart: {
type: 'scatter'
},
series: series
});
example: http://jsfiddle.net/w7ug4dbw/
There is important for the chart series that you will not have gaps in your category - so if you have categories 0 - 2, you need to have data for all 0,1,2 category - if you don't, then you can receive the errors while using the chart. To overcome that, you would need to loop through the series array and delete all the gaps.

Highchart: Plotting datetime chart issue when passing series map from java

I am trying to plot a datetime chart in highchart. I am passing series map from java HashMap and accessing it in js as:
var chartRoot = '#{value}'.evalJSON(true);
And feeding the map in series as:
series : [{color:'#057E7E',
data : chartRoot.series[0].y1axis,
name:'#{empty y1axistitle ? '' : y1axistitle}',
type: 'line',
tooltip: {
valuePrefix: ''
}
},{
color:'#FF8230',
data : chartRoot.series[0].y2axis,
name:'#{empty y2axistitle ? '' : y2axistitle}',
type: 'line',
tooltip: {
valuePrefix: '$'
},
yAxis: 1
}]
where y1axis and y2axis are hashMap with data for 2 y axis.
I am not able to plot graph like this. I even changed the type of hash map to but it did not work.
Please help me I am new to highchart.
Thanks in Advance.
It is problem with your data. Currently you have object:
{
1325376000000: 1.09,
1330560000000: 1.66,
1333238400000: 0.55,
more...
}
While there should be:
[
[1325376000000, 1.09],
[1330560000000, 1.66],
[1333238400000, 0.55],
more...
]
You can re-format this in JS:
var myData = [];
for (var time in chartRoot.series[0].y1axis) {
myData.push([time, chartRoot.series[0].y1axis[time]]);
}
And now use myData in series.data option.

How does one load a json encoded array as the x-axis for c3.js?

Pretty much the title. I have an array of serial numbers that I want to make as the x-axis. The array data itself was sucked up from a database via PHP. I then json_encode'd it and made it into a js array. The problem I'm having is that there is a separate section for both json: and columns: when generating a C3js graph.
var jsarray = <?php echo json_encode($array) ?>;
var chart = c3.generate({
bindto: '#chart',
data: {
x: 'js_array',
columns: [
['x', js_array]
],
json: {
Data_points,
Data_points2
},
axis: {
y: {
label: { // ADD
text: 'Y axis title',
position: 'outer-middle'
}
}
}
});
I tried looking for an example in the c3.js documentation, but they have separate sections for JSON data and formatting the x-axis. I didn't see a section where they combined the two though.
If I understand correctly, you're looking to be able to label the X-Axis data points while using JSON data, kind of like this example: http://c3js.org/samples/data_stringx.html ?
Assuming you have data in your PHP that looks something like this:
$php_data = array(
'x_labels' => array('MON', 'TUE', 'WED', 'THU', 'FRI'),
'data1' => array(30, 200, 100, 400, 150, 250),
'data2' => array(50, 20, 10, 40, 15, 25)
);
...then you should be able to achieve something similar to the example above using JSON data like so:
var json_data = <?php echo json_encode($php_data) ?>;
var chart = c3.generate({
bindto: "#chart",
data: {
x: 'x_labels',
json: json_data
},
axis: {
x: {
type: 'category'
},
y: {
label: 'number'
}
}
});
The data: { x: 'x_labels' } part tells the library to use the data under the array key "x_labels" at the axis labels, and then under axis: { x: { type: 'category' } }, we specify that we want to use strings for the label type rather than numbers. You don't have to specify this if your axis labels are numbers (e.g. 'x_labels' => array(1, 2, 3, 4, 5)).
Here's a jsfiddle if you want to play around with it:
https://jsfiddle.net/WingZero/Ldk4shLz/3/

Highcharts displays series names but missing data points from json source

I am using Highcharts with JSON data to render a standard line chart but am having some trouble getting the series data to display. The chart frame and series names appear on the page and everything checks out in the console, so I know that it has succeeded in fetching the data.
The JSON output appears valid when I run through JSONLint so I'm a little confused as to why this chart will not render correctly.
Here is my chart JAVASCRIPT CODE:
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'line',
zoomType: "x"
},
xAxis: {
type: 'datetime',
tickInterval: 7 * 24 * 3600 * 1000,
labels: {
format: '{value:%b %e, %Y}',
rotation: -45
},
},
yAxis: {
allowDecimals: true,
title: {
text: '$US'
}
},
tooltip: {
xDateFormat: '%b %e, %Y',
},
series: []
}
$.getJSON("mdb_ajax.php", function(json) {
options.series = new Array();
for(i=0;i< json.length;i++) {
options.series.push(json[i]);
}
var chart = new Highcharts.Chart(options);
});
});
Here's the corresponding PHP FILE:
$price_output = $prices->getPrices($filter_option);
foreach($price_output as $category => $price)
{
$arr[] = array('name' => $category, 'data' => $price);
}
print json_encode($arr);
As you can see I've jury-rigged the object to add "name" and "data" keys to aid Highcharts, but the object results in perfectly valid JSON without this additional work (it just won't display anything this way).
Here is a sample of the JSON DATA:
[
{
"name": "CTGY1",
"data": {
"1414998000000": "6.2400",
"1415084400000": "-3.1110",
"1415170800000": "1.5090",
"1415257200000": "4.2390",
"1415343600000": "1.6990",
"1426140000000": "5.9100"
},
{
"name": "CTGY2",
"data": {
"1414998000000": "7.7890",
"1415084400000": "-0.7610",
"1415170800000": "1.1600",
"1415257200000": "5.3300",
"1415343600000": "1.9290",
"1415602800000": "-0.8260"
}
]
I'm guessing there needs to be some definition of the key-values when processing the fetched JSON data, I'm just not sure what that would look like at this point. Any ideas on the best way to do this?
data should be an array and the Y-values should not be strings in your case:
data: [[1415602800000,-0.8260],[],...]
here are the acceptable data structures for data within series
http://api.highcharts.com/highcharts#series.data
Highcharts API also provide a few examples:
http://jsfiddle.net/gh/get/jquery/1.7.2/highslide-software/highcharts.com/tree/master/samples/highcharts/series/data-array-of-arrays/

Highcharts not plotting Date string as Category

I am using Highcharts to plot JSON Data. The dates are in the string format.
JSON Data:
[{"BRENT_SPOT":70.88,"TRADE_DATE":"31-JUL-2009"},{"BRENT_SPOT":73.28,"TRADE_DATE":"03-AUG-2009"},{"BRENT_SPOT":74.31,"TRADE_DATE":"04-AUG-2009"},{"BRENT_SPOT":74.96,"TRADE_DATE":"05-AUG-2009"},{"BRENT_SPOT":74.4,"TRADE_DATE":"06-AUG-2009"},{"BRENT_SPOT":72.84,"TRADE_DATE":"07-AUG-2009"},{"BRENT_SPOT":73.29,"TRADE_DATE":"10-AUG-2009"},{"BRENT_SPOT":72.04,"TRADE_DATE":"11-AUG-2009"}]
HighCharts / JQuery Code :
<script>
var chart;
$(function() {
var options = {
chart: {
renderTo: 'container',
zoomType: 'xy',
type: 'line'
},
title: {
text: 'Brent Daily Price Curve (FPC as at <cfoutput>#f_date#</cfoutput>)'
},
xAxis: {
labels: {
rotation: 45,
step: 3
},
type: 'category'
},
yAxis: {
lineWidth: 1,
title: {
text: '$ USD'
},
min: 0
},
series: []
};
$.getJSON("brentpricehc_test.cfm?f_date=<cfoutput>#f_date#</cfoutput>", {}, function(jsonResult) {
var BrentUSDPrice = {
name: "Brent Spot (USD)",
type: "line",
data: [],
marker: {
radius: 2
}
};
$(jsonResult).each(function(index) {
BrentUSDPrice.data.push([this.TRADE_DATE, this.BRENT_SPOT]);
});
/*options.series[0] = BrentUSDPrice;*/
options.series.push(BrentUSDPrice);
chart = new Highcharts.Chart(options);
});
});
</script>
I'm unable to plot any values wrt each of the date strings. I tried converting the JSON dates to datetime instead but still the same issue.
Few More details (for testing purposes):
Modifying to the below line plots the graph with the correct "brent_spot" values. This means that the issue lies with the way the "trade_dates" are 'not' plotting.
BrentUSDPrice.data.push([index, this.BRENT_SPOT]);
Edit 2 : (Using Datetime type to make the code work)
JSON Data (New): Returned as TO_CHAR(TRADE_DATE, 'YYYY/MM/DD')
[{"BRENT_SPOT":70.88,"TRADE_DATE":"2009\/07\/31"},{"BRENT_SPOT":73.28,"TRADE_DATE":"2009\/08\/03"},{"BRENT_SPOT":74.31,"TRADE_DATE":"2009\/08\/04"},{"BRENT_SPOT":74.96,"TRADE_DATE":"2009\/08\/05"},{"BRENT_SPOT":74.4,"TRADE_DATE":"2009\/08\/06"},{"BRENT_SPOT":72.84,"TRADE_DATE":"2009\/08\/07"},{"BRENT_SPOT":73.29,"TRADE_DATE":"2009\/08\/10"},{"BRENT_SPOT":72.04,"TRADE_DATE":"2009\/08\/11"}]
$(jsonResult).each(function(index) {
BrentUSDPrice.data.push([new Date(this.TRADE_DATE), this.BRENT_SPOT]);
});
Server side language used : Coldfusion
Database : Oracle
Am I doing something silly somewhere?
I have just tried your code, and it works perfectly fine, see: http://jsfiddle.net/3bQne/1026/
I guess, you need to update to Highcharts 3.0.10 to get this working.
If you are using type: 'category' then you need to assign name: to the data points. See the categories entry at http://api.highcharts.com/highcharts#xAxis
If categories are present for the xAxis, names are used instead of numbers for that axis. Since Highcharts 3.0, categories can also be extracted by giving each point a name and setting axis type to "category".
So the question is whether you are using Highcharts 3.0 and if you do then it needs to look something like this:
data: [{
name: 'Point 1',
color: '#00FF00',
y: 0
}, {
name: 'Point 2',
color: '#FF00FF',
y: 5
}]
see: http://api.highcharts.com/highcharts#series.data

Categories

Resources