I'm currently working on dynamically building column graphs in MVC, using C3 Charts. While I can bring the data from the database using AJAX/JSON, I am able to bind only the Y-Axis coordinates using the JSON property of C3, not the X-Axis categories.
What I want to do: Build column charts dynamically. For instance, the marks of students of multiple years will be calibrated as (Year 1: 50),(Year 2: 100) and so on, with the first part (category:Year) going on the X-Axis and the numeric part (Marks) going to the Y-Axis. The number of such combinations is dynamic, depending on the user's requirements (brought from the database as two columns, with multiple rows).
Problems I'm running into:
Specifying two different data types in the keys renders the non-numeric part (the category) as a separate series altogether, which I don't want and which isn't even working.
Whatever I do, the X-Axis comes with whole numbers depending on the number of columns visible. I'd like to change that to the actual category names.
Here is what I am doing. I took inspiration from Daniel's method here (https://groups.google.com/d/msg/c3js/RV1X18GZoGY/-p39m9Ngt-gJ)
$.ajax({
url: <Method in Controller here>,
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(parameters),
success: function (data) {
var myData = jQuery.parseJSON(data);
var testJson = $.map(myData, function (item) {
return {
Year: item.Year,
Marks: item.Marks
}
});
var chart = c3.generate({
bindto: '#chart',
size: {
width: 800
},
data: {
json: testJson,
mimeType: 'json',
keys: {
value: ['Marks']
},
}
});
}
});
Looking forward to some assistance. Thanks in advance!
Edit: I want the data to look like this in the end:
Sample Chart
You can try the following code:
var jsonTest = [
{ year: 1, marks: 50 },
{ year: 2, marks: 70 },
{ year: 3, marks: 75 },
{ year: 4, marks: 45 },
];
// The variable name chart will automatically bind itself to an id = chart
var chart = c3.generate({
data: {
type : 'bar',
json: jsonTest,
keys: {
x: 'year',
value: ['marks']
}
},
size: {
width: 400,
},
axis: {
x: {
type: 'category'
}
},
bar: {
width: {
ratio: 0.5
}
}
});
I was getting the following output:
Here's the JSBin example: Bar Chart Example
Related
Good morning.
I need to do the following: Update a stacked line chart using a function in javascript that takes a 2d array ([[0,1],[0,2],...]).
My page is running in a Java fx webview so I can dynamically update my data. All the examples I've seen so far create a predefined X axis and pass the y values accordingly, I wanted to pass the two values together to plot a line on the chart.
How could I make this function? It's the first time I use echarts so I'm lost.
I even managed to do something similar but when plotting the chart it was all wrong.
Char Image
var option = {
xAxis: {
type: "value",
},
yAxis: {
type: "value",
},
series: [
{
type: "line",
data: [],
},
],
};
vibrationStackedLineChart.setOption(option);
function updateEchart(dataArray) {
// Parse the JSON string back into a 2D int array
var data = JSON.parse("[" + dataArray + "]");
// Update the chart with the new data
vibrationStackedLineChart.setOption({
series: [
{
data: data,
},
],
});
}
Java function with array 2d
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/
I use highcharts for draw charts. I have 2d json object and I don't know how to set this object to highcharts. And this is my json object data:
And I want my chart like this picture(column-parsed example of highchart):
And this is my code:
$.ajax({
url:"../../teachersem",
type:"get",
data:{
id:$.trim(tableData[0])
},
success:function(data){
$('div[class|="col-md-7 col-md-offset-3"]').css("display","none");
//console.log(data.accept);
//console.log(data.fail);
var accept=new Array();
var fail =new Array();
for (i = 0; i < data.accept.length; i++){
accept.push([data.accept[i].year, parseInt(data.accept[i].count)]);
alert("accept: "+data.accept[i].year+" "+parseInt(data.accept[i].count));
}
//console.log(accept.toString());
for (i = 0; i < data.fail.length; i++){
fail.push([data.fail[i].year, parseInt(data.fail[i].count)]);
alert("fail: "+data.fail[i].year+" "+parseInt(data.fail[i].count));
}
$('#container').highcharts({
chart: {
type: "column"
},
title: {
text: "Student data"
},
xAxis: {
allowDecimals: false,
title: {
text: "Branch of studies"
}
},
yAxis: {
title: {
text: "Number of students"
}
},
series: [{
data: [accept,fail]
}],
});
},
error:
alert('error!')
})
});
But this has any result? please help,thank u!
You actually want two series: data parameters (one for each column).
The first column will be the accept data and the second column will be your fail data since I am guessing that your category label which in the example image is Apples will be a Branch of Studies.
Your series should look something similar to the following:
series: [{
name: "Accept",
data: accept,
},
{
name: "Fail",
data: fail,
}]
Your accept and fail arrays are currently arrays of arrays, but they can actually be a simple list as seen in the Highcharts demo here. You can then specify in the xAxis parameter the categories: that are your Branch of Studies.
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
I am trying to plot a pie chart with data set containing zero values.But pie chart shows only labels till data gets updated.
What if I wanted to show empty pie chart.
I have given:
var data = [
{
label: "Series1",
data: 0,
url: "http://stackoverflow.com"},
{
label: "Series2",
data: 0,
url: "http://serverfault.com"},
{
label: "Serie3",
data: 0,
url: "http://superuser.com"},
{
label: "Series4",
data: 0,
url: "http://www.google.com"},
{
label: "Series5",
data: 0,
url: "http://www.oprah.com"},
{
label: "Series6",
data: 0,
url: "http://www.realultimatepower.net/"}
];
var options = {
series: {
pie: {
show: true
}
},
grid: {
hoverable: true
}
};
var plot = $.plot($("#graphLoaderDiv"), data, options);
Modify your label formatter function to return null if the series percent is zero.
After digging deeper I realized The best possible solution is to not to show pie chart if your data set values are zero.You either can do it editing following plugin or adding check inside your plotting function.
Download jquery.flot.pie.js from here
http://code.google.com/p/flot/issues/detail?id=530
Go to line No 411 and modify code as follows.
if( isNaN(angle) ) {
//var html = html = '<span class="pieLabel" id="pieLabelNoData" style="position:absolute;top:20px;left:5px;">There is no available data.</span>';
//html = target.append(html);
target.hide();
}
you can show empty data like this
$piedata="[{label:'no data',data:1}]";