How to show legends on chart using c3 js with json - javascript

I'm using C3 chart to present some data on my project and I want to show up legends (Label in my case) instead of numbers in the AcisX :
Data json format :
[
{"Label":"DQUA","Aut":3.75,"NoAut":3.75,"CM":32},
{"Label":"DPRO","Aut":43.9,"NoAut":0,"CM":144},
{"Label":"DMAI","Aut":1.6999999999999993,"NoAut":0,"CM":0},
{"Label":"DENG","Aut":0,"NoAut":0,"CM":16}
]
My attempt to get the task work :
var chart = c3.generate({
bindto: '.ks-chart-orders-block',
data: {
url: '/Home/AbsencesByDepartementFiltredByReasons',
mimeType: 'json',
type:'bar',
keys:{
value: ['Aut','NoAut','CM']
},
}
}
});
Getted Result :
Expected Result:

You need to modify the x-axis with a custom category:
var chart = c3.generate({
bindto: '.ks-chart-orders-block',
data: {
url: '/Home/AbsencesByDepartementFiltredByReasons',
mimeType: 'json',
type:'bar',
keys:{
x: 'Label',
value: ['Aut','NoAut','CM']
},
},
axis: {
x: {
type: 'category',
tick: {
centered: true
}
}
}
});

Related

How to display grouped data in ChartJs

I have the following array:
Where the arrays keys are the dates and the only element I want to plot, of each set, is the weight. Look:
I am putting the code as follows. Notice that I am already grouping in the date attribute the whole set belonging to each that key.
var ctx = document.getElementById("barChart").getContext("2d");
var data = {
labels: ['21/03/2018','01/04/2018','02/04/2018','04/04/2018','05/04/2018','06/04/2018'],
datasets: [
{
label: '21/03/2018',
data: [12, 0, 0]
},
{
label: '01/04/2018',
data: [15.00, 15.00,15.00]
},
{
label: '02/04/2018',
data: [25.00, 25.00, 25.00]
},
{
label: '04/04/2018',
data: [25.00, 25.00, 25.00]
},
{
label: '05/04/2018',
data: [-8.14,-7.93, -7.84]
},
{
label: '06/04/2018',
data: [-35.9 ,-38.1, -37.5]
},
]
};
var myBarChart = new Chart(ctx, {
type: 'bar',
data: data,
});
But in this way ChartJs does not understand that it only needs to plot the data set present in the "data" attribute and grouping them by the key. Plotting the graph in the wrong way.
How could I plot the data correctly knowing that they are already grouped?
You need to organize your data as such:
var ctx = document.getElementById("canvas").getContext("2d");
var data = {
labels: ['21/03/2018','01/04/2018','02/04/2018','04/04/2018','05/04/2018','06/04/2018'],
datasets: [
{
data: [12, 15.00, 25.00, 25.00, -8.14, -35.9]
},{
data: [0, 15.00, 25.00, 25.00, -7.93, -38.1]
},{
data: [0, 15.00, 25.00, 25.00, -7.84, -37.5]
}
]
};
var myBarChart = new Chart(ctx, {
type: 'bar',
data: data,
options:{
legend: 'none'
}
});
I took your legend out as it's useless in this case. To look at it in the coding persepective, whatever index the date in labels is at needs to correlate with the index of the information you want to display in that grouping. data[0] refers to labels[0] and so on.

C3js change axis time format on load

I have a C3.js chart with time values formatted per minute as %H:%M.
Now I want to load new data, but instead of data per hour I want to show the data per day as %d-%m.
So the tick format needs to change, but how do I do this?
chart generation with C3.js
chart = c3.generate({
bindto: element,
data: {
x: "keys",
xFormat: '%Y-%m-%d %H:%M:%S',
url: dataurl + '/today',
mimeType: 'json',
type: 'bar',
},
axis: {
x: {
type: 'timeseries',
tick: {
format: '%H:%M'
}
}
}
});
Loading new data
chart.load({
x: "keys",
xFormat: '%Y-%m-%d %H:%M:%S',
url: url,
mimeType: 'json',
});
Latest from Masayuki on Github - said there was no API for that.
But you can define a global variable to change ticks dynamically, see Masayuki's fiddle
From Github -
var formatter;
function updateFormatter(byMonth) {
formatter = d3.time.format(byMonth ? '%Y-%m' : '%Y-%m-%d')
}
updateFormatter();
var chart = c3.generate({
data: {
x: 'date',
columns: [
['date', '2014-01-01', '2014-01-02', '2014-01-03'],
['data1', 100, 200, 300],
]
},
axis: {
x: {
type: 'timeseries',
tick: {
format: function (x) { // x comes in as a time string.
return formatter(x);
}
}
}
}
});
d3.select('#btnByMonth').on('click', function () {
updateFormatter(true);
chart.flush();
});
d3.select('#btnByWeek').on('click', function () {
updateFormatter(false);
chart.flush();
});

Reloading HighCharts data using Ajax

I'm trying to replace the highcharts that I loaded using ajax. Apparently what I am doing is that I would get new values from the user, send the new values thru Ajax, then return an entirely new graph(different graph type with different data) so what I'm doing is this:
$.ajax({
type: "POST",
url: $("#searchForm").attr( 'action' ),
data: $("#searchForm").serialize(),
success: function(response) {
$('#container').highcharts({ response });
}
});
But what happens is that it just loads a blank graph.
this is my highcharts code:
chart: { type: 'bubble', zoomType: 'xy'}, title: { text: 'Day at a Glance' }, tooltip: {}, xAxis:
{categories:[ 'Delta Air Lines' ]}, yAxis: { title: { text: '# of Crew' } }, series: [{name: '# of
Passengers', URLs:[ '#'], data: [['1',1,0]], point: { events: {click: function() { var someURL =
this.series.userOptions.URLs[this.x]; if (someURL) window.open('http://'+someURL); }}} }]
Is there something wrong with the way I call my ajax or there is something wrong with my highcharts code?
In the response you need to get json, like
{
chart:{
//any options
},
series: [{
data:[1,2,3] //any points
}]
}
So you cannot use something like highcharts({ response }) but highcharts(response)

Highcharts Pyramid Chart displays no data with JSON, PHP

When using JSON with a pyramid chart in Highcharts, I don't get any errors in the console log but no data is displayed.
I have charts.php which outcome is this:
{"success":1,"data":[{"name":"John Spoon","data":300}, {"name":"Dave Jones","data":200},{"name":"Other","data":500}]}
This is what I've tried, which returns no data.
<div id="chart" style=
"height:600px;width:100%;"></div>
<script>
$(function () {
$("#chart").html("Loading Activity Log Graph...");
var options = {
chart: {
type: 'pyramid',
renderTo: 'chart',
marginRight: 100
},
title: {
text: 'Activity',
x: -50
},
plotOptions: {
series: {
dataLabels: {
enabled: true,
format: '<b>{point.name}</b> ({point.y:,.0f})',
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black',
softConnector: true
}
}
},
legend: {
enabled: false
},
name: 'Activity Count',
series: [{}]
};
$.ajax({
url: "charts.php",
type:'post',
dataType: "json",
success: function(data){
options.series = data.data;
var chart = new Highcharts.Chart(options);
}
});
});
</script>
This is my desired outcome, showing without the use of JSON:
http://jsfiddle.net/0dyy44hz/
What do I need to change for it to show data?
Looking at the pyramid example, the data must be in the form of a single series with each data point as an array of [name, value]. You have two options, change your PHP to output the correct format or modify the PHP output in javascript. Since you didn't post your PHP code, I'll do the later:
var data = {"success":1,"data":[{"name":"John Spoon","data":300}, {"name":"Dave Jones","data":200},{"name":"Other","data":500}]};
options.series = [{
data: $.map(data.data, function(i){ // loop outputted data
return [[i.name, i.data]]; // coerce into an array of [name,value]
})
}];
Here's a working example.

HighCharts with options

I currently have a working chart using this:
$.ajax({
type: "GET",
url: graphURL,
data: "",
cache: false,
success: function (response) {
//alert(response);
jsonData = JSON.parse(response);
if(jsonData != '' && jsonData != null) {
var category = jsonData.XData.split(",");
var series = jsonData.YData.split(",");
series = $.each(series, function (i, amt) {
series[i] = parseFloat(series[i]);
});
//Display chart
UserChart(series, category, jsonData.YAxisTitle);
}
}
});
... but it doesn't allow me to set options like if I wanted an area chart instead of line etc.. how do I modify the code so I could include something like the following which I see in all examples:
chart : {
renderTo : 'container'
},
rangeSelector : {
selected : 1
},
title : {
text : 'AAPL Stock Price'
},
series : [{
name : 'AAPL Stock Price',
data : data,
type : 'area',
threshold : null,
tooltip : {
valueDecimals : 2
},
fillColor : {
linearGradient : {
x1: 0,
y1: 0,
x2: 0,
y2: 1
},
stops : [[0, Highcharts.getOptions().colors[0]], [1, 'rgba(0,0,0,0)']]
}
}]
The problem is that series is the series points' data.
Try to pass a serie to UserChart.
Like the following:
var points = jsonData.YData.split(",");
points = $.each(series, function (i, amt) {
points[i] = parseFloat(series[i]);
});
// here you set your serie config
var serie = {
name: 'AAPL Stock Price',
type: 'area',
data: points,
threshold : null,
tooltip : {
valueDecimals : 2
}
};
UserChart(serie, category, jsonData.YAxisTitle);
Then in UserChart you should add the serie directly to the chart series.
Example:
var options: {
chart : {
renderTo : 'container'
},
rangeSelector : {
selected : 1
},
title : {
text : 'AAPL Stock Price'
},
series : []
};
function UserChart(serie, category, jsonData.YAxisTitle) {
options.series.push(serie);
// add your code
}

Categories