I am trying to figure out how to combine 3 ajax call into 1 but so far I didn't find out the correct way to do it. I have the following three highcharts:
chart1 = new Highcharts.Chart({
chart: {
height: 155,
renderTo: 'chart1_div',
defaultSeriesType: 'spline',
events: {
load: GetData1(date)
}
},
plotOptions: {
series: {
fillOpacity: 0.1
}
},
xAxis: {
categories: c,
labels: {
staggerLines: 2
}
},
yAxis: {
gridLineColor: "#ffffcc",
title: {
text: ''
},
labels: {
x: 15,
y: 15,
style: {
color: "#999999",
//fontWeight: "bold",
fontSize: "10px"
}
},
},
series: [{
name: 'Chart1',
color: "#6bd9ec", //37f312
data: chart1_data
}]
});
chart2 = new Highcharts.Chart({
chart: {
height: 155,
renderTo: 'chart2_div',
defaultSeriesType: 'spline',
events: {
load: GetData2(date)
}
},
plotOptions: {
series: {
fillOpacity: 0.1
}
},
xAxis: {
categories: c,
labels: {
staggerLines: 2
}
},
yAxis: {
gridLineColor: "#ffffcc",
title: {
text: ''
},
labels: {
x: 15,
y: 15,
style: {
color: "#999999",
//fontWeight: "bold",
fontSize: "10px"
}
},
},
series: [{
name: 'Chart2',
color: "#6bd9ec", //37f312
data: chart2_data
}]
});
chart3 = new Highcharts.Chart({
chart: {
height: 155,
renderTo: 'chart3_div',
defaultSeriesType: 'spline',
events: {
load: GetData3(date)
}
},
plotOptions: {
series: {
fillOpacity: 0.1
}
},
xAxis: {
categories: c,
labels: {
staggerLines: 2
}
},
yAxis: {
gridLineColor: "#ffffcc",
title: {
text: ''
},
labels: {
x: 15,
y: 15,
style: {
color: "#999999",
//fontWeight: "bold",
fontSize: "10px"
}
},
},
series: [{
name: 'Chart3',
color: "#6bd9ec", //37f312
data: chart3_data
}]
});
At the moment I am making three different ajax calls:
function GetData1(date) {
$.ajax({
url: '/GetAjaxCall',
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ date: date }),
success: function (f) {
var cat= [];
var ser= [];
$.each(f.d, function (i, e) {
cat.push(e.date);
ser.push(parseInt(e.val1));
});
chart1_div.xAxis[0].setCategories(cat);
chart1_div.series[0].setData(ser);
},
error: function (e) {
alert(e.statusText);
},
cache: false
});
}
function GetData2(date) {
$.ajax({
url: '/GetAjaxCall',
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ date: date }),
success: function (f) {
var cat= [];
var ser= [];
$.each(f.d, function (i, e) {
cat.push(e.date);
ser.push(parseInt(e.val2));
});
chart2_div.xAxis[0].setCategories(cat);
chart2_div.series[0].setData(ser);
},
error: function (e) {
alert(e.statusText);
},
cache: false
});
}
function GetData3(date) {
$.ajax({
url: '/GetAjaxCall',
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ date: date }),
success: function (f) {
var cat= [];
var ser= [];
$.each(f.d, function (i, e) {
cat.push(e.date);
ser.push(parseInt(e.val3));
});
chart3_div.xAxis[0].setCategories(cat);
chart3_div.series[0].setData(ser);
},
error: function (e) {
alert(e.statusText);
},
cache: false
});
}
As you can see, I am right now making the same ajax call 3 times just to be able to populate the 3 charts differently. Does anyone know how could I generate exactly the same 3 charts but only make 1 ajax call? Thanks a lot
Something like:
function GetDataAll(date) {
$.ajax({
url: '/GetAjaxCall',
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ date: date }),
success: function (f) {
var cat1= [];
var ser1= [];
var cat2= [];
var ser2= [];
var cat3= [];
var ser3= [];
$.each(f.d, function (i, e) {
cat1.push(e.date);
ser1.push(parseInt(e.val1));
});
chart1_div.xAxis[0].setCategories(cat1);
chart1_div.series[0].setData(ser1);
chart2_div.xAxis[0].setCategories(cat2);
chart2_div.series[0].setData(ser2);
chart3_div.xAxis[0].setCategories(cat3);
chart3_div.series[0].setData(ser3);
},
error: function (e) {
alert(e.statusText);
},
cache: false
});
}
Under the load event I could call GetData1(date) for the 3 charts but this way I will be hitting the ajax call 3 times. I am probably doing this the wrong way and must be a more efficient way. I will appreciate any thoughts, thank you so much
EDITED - LATEST UPDATE THAT WORKS BASED ON #WERGELD HELP
var chart1_options = {
chart: {
renderTo: 'chart1_div',
xAxis: {
categories: []
},
series: [{
name: 'Chart1',
color: "#6bd9ec"
}]
};
var chart2_options = {
chart: {
renderTo: 'chart2_div',
xAxis: {
categories: []
},
series: [{
name: 'Chart2',
color: "#6bd9ec"
}]
};
var chart3_options = {
chart: {
renderTo: 'chart3_div',
xAxis: {
categories: []
},
series: [{
name: 'Chart3',
color: "#6bd9ec"
}]
};
function GetDataAll(date) {
$ajax({..
chart1_options.xAxis.categories = cat1;
chart1_options.series[0].data = ser1;
chart2_options.xAxis.categories = cat2;
chart2_options.series[0].data = ser2;
chart3_options.xAxis.categories = cat3;
chart3_options.series[0].data = ser3;
var chart1 = new Highcharts.Chart(Highcharts.merge(options, chart1_options));
var chart2 = new Highcharts.Chart(Highcharts.merge(options, chart2_options));
var chart3 = new Highcharts.Chart(Highcharts.merge(options, chart3_options));
});
}
Here is some psuedo code to get you going. What you need to do is setup a chart option object that contains all the constant items among your charts:
var options = {
chart: {
height: 155,
defaultSeriesType: 'spline'
},
plotOptions: {
series: {
fillOpacity: 0.1
}
},
xAxis: {
categories: c,
labels: {
staggerLines: 2
}
},
yAxis: {
gridLineColor: "#ffffcc",
title: {
text: ''
},
labels: {
x: 15,
y: 15,
style: {
color: "#999999",
//fontWeight: "bold",
fontSize: "10px"
}
},
}
};
Next you do your ajax call and assign your series' data and title (and any other items) and create an object for each chart you want to create:
var chartOptions1 = {
chart: { renderTo: 'container1' },
series: []
};
var chartOptions2 = {
chart: { renderTo: 'container1' },
series: []
};
Next you do your code to get the chart data/name/etc that you want to have for each chart which I will not go into here. The next step is to then create your chart from the merged options:
var chart1 = new Highcharts.Chart(Highcharts.merge(options, chartOptions1));
var chart2 = new Highcharts.Chart(Highcharts.merge(options, chartOptions2));
This should do it. Again, it is psuedocode but you get the idea. Global options + merge are you friends. Full psuedocode here.
I have a chart below that does not work with AJAX request.
function ajaxGraficoBarraUnidade() {
var strSeries = "";
var strDrilldown = "";
$.ajax({
type: "POST",
data: window.formData + '&strMundo=' + "<?php echo ($strMundo); ?>" + '&strGraph=Unidade',
dataType: "json",
url: "ajaxBlitzCarregamentoGrafico.php",
beforeSend: function () {
},
success: function (strRetorno) {
strSeries = strRetorno.geos;
strDrilldown = strRetorno.unidades;
carregaGraficoBarraUnidade(strSeries, strDrilldown);
},
error: function (txt) {
}
});
}
function carregaGraficoBarraUnidade(strSeries, strDrilldown) {
$('#divGraficoBarraUnidade').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Browser market shares. January, 2015 to May, 2015'
},
subtitle: {
text: 'Click the columns to view versions. Source: netmarketshare.com.'
},
xAxis: {
type: 'category'
},
yAxis: {
title: {
text: 'Total percent market share'
}
},
legend: {
enabled: false
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
format: '{point.y:.1f}%'
}
}
},
tooltip: {
headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y:.2f}%</b> of total<br/>'
},
series: strSeries,
drilldown: {
series: strDrilldown
}
});
</code>
I have a return equal to ajax below:
{'geos':[{'name': 'Regionais','data': [{'name':'Geo CO','y':1.59,'drilldown':'Geo CO'},{'name':'Geo MG/ES','y':4.41,'drilldown':'Geo MG/ES'},{'name':'Geo NE','y':3.35,'drilldown':'Geo NE'},{'name':'Geo NO','y':1.96,'drilldown':'Geo NO'},{'name':'Geo PR/SPI','y':0.10,'drilldown':'Geo PR/SPI'},{'name':'Geo RJ','y':1.81,'drilldown':'Geo RJ'},{'name':'Geo RS/SC','y':0.75,'drilldown':'Geo RS/SC'},{'name':'Geo SPC','y':0.33,'drilldown':'Geo SPC'}]}], 'unidades':[{'name':'Geo CO','id':'Geo CO','data': [['CDC Araguaina',1.30],['CDC Catalao',0.01],['CDC Formosa',4.70],['CDC Porto Velho',0.29],['CDC Rio Branco',0.00],['CDC Rio Verde',0.12],['CDC Rondonopolis',5.15],['CDC Tangara',0.51],['CDD Brasilia',0.06],['CDD Brasilia Int',2.67],['CDD Caceres',0.05],['CDD Campo Gde',0.00],['CDD Cuiaba Int',0.03],['CDD Goiania Int',0.00],['CDD Itumbiara',38.19],['CDD Manaus',0.43]]},{'name':'Geo MG/ES','id':'Geo MG/ES','data': [['CDD Alfenas',0.02],['CDD Cachoeiro',0.28],['CDD Ipatinga',0.03],['CDD João Monlevade DDC',0.00],['CDD Minas Int',0.77],['CDD Poços de Caldas',0.91],['CDD Pouso Alegre',0.17],['CDD Uberaba',0.08],['CDD Uberlandia',0.07],['CDD Vitoria',25.62],['CDL AS Minas',0.01],['CDL Santa Luzia',2.70]]},{'name':'Geo NE','id':'Geo NE','data': [['CDC Arapiraca',0.12],['CDC Lapa',0.32],['CDD Aracaju',0.05],['CDD Caruaru',8.05],['CDD F. de Santana',0.17],['CDD Guanambi',0.01],['CDD Ilheus',0.03],['CDD Maceio',0.06],['CDD Olinda',0.16],['CDD Rib. Pombal',0.04],['CDD Salvador',0.17],['CDD Vit. da Conquista',0.06],['CDL Cabo',1.33],['CDL Jequie',0.06]]},{'name':'Geo NO','id':'Geo NO','data': [['CDD Aracati',0.02],['CDD Balsas',0.08],['CDD Belem',0.02],['CDD Campina Grande',0.03],['CDD Fortaleza',0.03],['CDD Imperatriz',0.02],['CDD Joao Pessoa Int',5.86],['CDD Maranhao Int ',12.72],['CDD Natal Int',0.02],['CDD Sul Maranhão',0.03],['CDL Ceara',0.37]]},{'name':'Geo PR/SPI','id':'Geo PR/SPI','data': [['CDC Beltrao',0.00],['CDD Agudos Int',0.12],['CDD Araçatuba',0.07],['CDD Araraquara',0.02],['CDD Bebedouro',0.09],['CDD Curitiba',0.00],['CDD Jaú',3.19],['CDD Londrina',0.00],['CDD Mogi Mirim',0.04],['CDD Ponta Grossa',0.37],['CDD Presidente Prudente',0.05],['CDD Rib. Preto',0.04],['CDL Paranagua',0.02]]},{'name':'Geo RJ','id':'Geo RJ','data': [['CDD Campos',1.18],['CDD Jacarepagua',1.65],['CDD Niteroi',0.02],['CDD Nova Friburgo',0.01],['CDD Nova Iguacu',0.02],['CDD Petropolis',0.00],['CDD RJ Campo Gde Int',3.77],['CDD S. Cristovao',0.81],['CDL Itaperuna',0.14]]},{'name':'Geo RS/SC','id':'Geo RS/SC','data': [['CDD Blumenau',0.07],['CDD Camboriu',0.11],['CDD Caxias do Sul',0.07],['CDD Florianopolis',0.12],['CDD Pelotas',0.04],['CDD Porto Alegre',1.06],['CDD S. Cruz Sul',0.02],['CDD Santa Maria',0.45],['CDD Sapucaia Int',2.66]]},{'name':'Geo SPC','id':'Geo SPC','data': [['CDD Campinas',0.12],['CDD Diadema',0.72],['CDD Guarulhos',0.23],['CDD Jundiai',1.04],['CDD Litoral SP',0.05],['CDD Mooca',1.05],['CDD Norte',0.10],['CDD Oeste',0.04],['CDD Praia Grande',0.06],['CDD São José dos Campos',0.54],['CDD Sul SP',0.00],['CDD Taubaté',0.82],['CDD Votorantin',0.77]]}]}
It does not recognize the values passed in SERIES. I do not think the error. Does anyone know what might be happening? Tanks!
What might be happening is your data is getting loaded after the chart is created, so I've changed the format to be as shown in the Highcharts documentation, but tried not to change to much otherwise.
Highcharts documentation on working with data
See a plunkr demo with your chart working with available data
The data is hosted on myjson.com as JSON, so I changed the POST to a GET request.
Here is the key HTML code:
<script src="https://code.jquery.com/jquery-3.0.0.min.js" integrity="sha256-JmvOoLtYsmqlsWxa7mDSLMwa6dZ9rrIdtrrVYRnDRH0=" crossorigin="anonymous"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<div id="divGraficoBarraUnidade" style="width:100%; height:400px;"></div>
This is the Javascript / jQuery code:
$(function () {
$(document).ready(function() {
var options = {
chart: {
renderTo: 'divGraficoBarraUnidade',
type: 'column'
},
title: {
text: 'Browser market shares. January, 2015 to May, 2015'
},
subtitle: {
text: 'Click the columns to view versions. Source: netmarketshare.com.'
},
xAxis: {
type: 'category'
},
yAxis: {
title: {
text: 'Total percent market share'
}
},
legend: {
enabled: false
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
format: '{point.y:.1f}%'
}
}
},
tooltip: {
headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y:.2f}%</b> of total<br/>'
},
series: {},
drilldown: {
series: {}
}
};
function ajaxGraficoBarraUnidade() {
$.ajax({
type: "GET",
data: window.formData + '&strMundo=' + "<?php echo ($strMundo); ?>" + '&strGraph=Unidade',
dataType: "json",
url: "https://api.myjson.com/bins/42c59",
beforeSend: function () {
},
success: function (strRetorno) {
options.series = strRetorno.geos;
options.drilldown.series = strRetorno.unidades;
var chart = new Highcharts.Chart(options);
console.log('options', options)
},
error: function (txt) {
// Report errors here...
}
});
}
ajaxGraficoBarraUnidade();
});
});
I've spent a lot of time with c3's documentation and examples, but have not been able to find a a way to unload or hide a category from a chart using API functions. Removing lines or bars is easy, but removing x-axis categories is proving more challenging. Here is a streamlined version of my chart.
var genderChart = c3.generate({
bindto: '#chart-gender',
data: {
json: [
{
Disease:"Mumps",
"Female":231,
"Male":198
},
Disease:"Tuberculosis",
"Female":18,
"Male":197
}
],
type: 'bar',
keys: {
x: "Disease",
value: ["Female","Male"]
},
selection: {
enabled: true,
grouped: true
},
},
axis: {
x: {
type: 'category',
}
},
});
I would like to dynamically show and hide (load and unload) diseases. For instance, I would like to be able to toggle Tuberculosis on and off. My actual chart has a number of other diseases. If I structured the data such that the diseases were bars and gender was on the x-axis, this would be easy. However, that is not comparison I wish to show with this chart. Is this possible with c3? How do I select all of the values with a given x value (disease) and then unload those data points? I appreciate any insight.
I would build up the json data object and then re-render the chart.
Here's an example:
var data = [{
Disease: "Mumps",
Female: 231,
Male: 198
}, {
Disease: "Tuberculosis",
Female: 18,
Male: 197
}];
$("button").click(function () {
Render();
});
Render()
function Render() {
var selectedData = [];
if ($("#mumps").prop("checked")) selectedData.push(data[0]);
if ($("#tb").prop("checked")) selectedData.push(data[1]);
var genderChart = c3.generate({
data: {
json: selectedData,
type: 'bar',
keys: {
x: "Disease",
value: ["Female", "Male"]
},
selection: {
enabled: true,
grouped: true
},
},
axis: {
x: {
type: 'category',
}
},
});
}
Here's the code in a fiddle:
http://jsfiddle.net/ot19Lyt8/14/