Commit ad50aa10 authored by Rodrigo Tapia-McClung's avatar Rodrigo Tapia-McClung

Improve bar chart creation

parent 41916715
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
*/ */
/* globals updateBarChart, barChartData, am4charts, am4core, am4themes_animated, yearList */ /* globals updateBarChart, barChartData, am4charts, am4core, am4themes_animated, yearList */
/* export makeRadialChart, makeLineChart */ /* export makeRadialChart, makeLineChart, makeAreaChart, makeBarChart */
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function grijalva_theme(target) { function grijalva_theme(target) {
...@@ -35,7 +35,12 @@ function customizeGrip(grip) { ...@@ -35,7 +35,12 @@ function customizeGrip(grip) {
img.align = "center"; img.align = "center";
img.valign = "middle"; img.valign = "middle";
} }
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ RADAR- LINES
// Themes begin
am4core.useTheme(am4themes_animated);
am4core.useTheme(grijalva_theme);
//let mainTextColor = getComputedStyle(document.body).getPropertyValue('--main-text-color');
// Themes end
let mainTextColor = getComputedStyle(document.body).getPropertyValue('--main-text-color'); let mainTextColor = getComputedStyle(document.body).getPropertyValue('--main-text-color');
...@@ -65,14 +70,14 @@ const makeRadialRange = (axis, start, end, color, span) => { ...@@ -65,14 +70,14 @@ const makeRadialRange = (axis, start, end, color, span) => {
} }
const makeLineAxisAndSeries = (chart, field, name, opposite, bullet) => { const makeLineAxisAndSeries = (chart, field, name, opposite, bullet) => {
var lineValueAxis = chart.yAxes.push(new am4charts.ValueAxis()); let lineValueAxis = chart.yAxes.push(new am4charts.ValueAxis());
lineValueAxis.fontSize = 8; lineValueAxis.fontSize = 8;
if (chart.yAxes.indexOf(lineValueAxis) != 0) { if (chart.yAxes.indexOf(lineValueAxis) != 0) {
lineValueAxis.syncWithAxis = chart.yAxes.getIndex(0); lineValueAxis.syncWithAxis = chart.yAxes.getIndex(0);
} }
var lineSeries = chart.series.push(new am4charts.LineSeries()); let lineSeries = chart.series.push(new am4charts.LineSeries());
lineSeries.dataFields.valueY = field; lineSeries.dataFields.valueY = field;
lineSeries.dataFields.dateX = "date"; lineSeries.dataFields.dateX = "date";
lineSeries.strokeWidth = 2; lineSeries.strokeWidth = 2;
...@@ -93,7 +98,7 @@ const makeLineAxisAndSeries = (chart, field, name, opposite, bullet) => { ...@@ -93,7 +98,7 @@ const makeLineAxisAndSeries = (chart, field, name, opposite, bullet) => {
const makeDateRange = (axis, start, width, color) => { const makeDateRange = (axis, start, width, color) => {
yearList.forEach( y => { yearList.forEach( y => {
var range = axis.axisRanges.create(); let range = axis.axisRanges.create();
range.date = new Date(y, start, 1, 0, 0, 0); range.date = new Date(y, start, 1, 0, 0, 0);
range.endDate = new Date(y, start+width, 1, 0, 0, 0); range.endDate = new Date(y, start+width, 1, 0, 0, 0);
range.axisFill.fill = am4core.color(color); range.axisFill.fill = am4core.color(color);
...@@ -117,6 +122,29 @@ const makeAreaSeries = (chart, field, name) => { ...@@ -117,6 +122,29 @@ const makeAreaSeries = (chart, field, name) => {
return areasSeries; return areasSeries;
} }
const makeBarSeries = (chart, field, name) => {
let barSeries = chart.series.push(new am4charts.ColumnSeries());
barSeries.dataFields.valueY = field;
barSeries.dataFields.categoryX = "grupo";
barSeries.dataFields.categoryX = "grupo"; //"year";
barSeries.name = name;
barSeries.columns.template.tooltipText = "[underline][bold]Menor a [bold]{categoryX.formatNumber('#,###.#')} Ha[/]: {valueY.formatNumber('#,###.#')} cuerpos[/]";
barSeries.columns.template.height = am4core.percent(100);
barSeries.sequencedInterpolation = true;
let barValueLabel = barSeries.bullets.push(new am4charts.LabelBullet());
barValueLabel.label.text = "{valueY}";
barValueLabel.label.horizontalCenter = "middle";
barValueLabel.label.dx = 3;
barValueLabel.label.dy = -5;
barValueLabel.label.hideOversized = false;
barValueLabel.label.truncate = false;
barValueLabel.fontSize = 10;
//barValueLabel.label.fill = am4core.color(mainTextColor);
barValueLabel.label.fill = am4core.color("#fff");
}
const makeRadialChart = (data, months, years) => { const makeRadialChart = (data, months, years) => {
let radialChart = am4core.create("radial_chart", am4charts.RadarChart); let radialChart = am4core.create("radial_chart", am4charts.RadarChart);
...@@ -203,7 +231,7 @@ const makeLineChart = (data) => { ...@@ -203,7 +231,7 @@ const makeLineChart = (data) => {
lineChart.data = data; lineChart.data = data;
var lineDateAxis = lineChart.xAxes.push(new am4charts.DateAxis()); let lineDateAxis = lineChart.xAxes.push(new am4charts.DateAxis());
lineDateAxis.renderer.minGridDistance = 50; lineDateAxis.renderer.minGridDistance = 50;
lineDateAxis.fontSize = 8; lineDateAxis.fontSize = 8;
lineDateAxis.renderer.labels.template.fill = am4core.color(mainTextColor); lineDateAxis.renderer.labels.template.fill = am4core.color(mainTextColor);
...@@ -242,7 +270,7 @@ const makeAreaChart = (data) => { ...@@ -242,7 +270,7 @@ const makeAreaChart = (data) => {
areaChart.data = data; areaChart.data = data;
// chart.dateFormatter.inputDateFormat = "dd-mm-yyyy"; // chart.dateFormatter.inputDateFormat = "dd-mm-yyyy";
var areaDateAxis = areaChart.xAxes.push(new am4charts.DateAxis()); let areaDateAxis = areaChart.xAxes.push(new am4charts.DateAxis());
areaDateAxis.renderer.minGridDistance = 60; areaDateAxis.renderer.minGridDistance = 60;
areaDateAxis.fontSize = 8; areaDateAxis.fontSize = 8;
areaDateAxis.renderer.labels.template.fill = am4core.color(mainTextColor); areaDateAxis.renderer.labels.template.fill = am4core.color(mainTextColor);
...@@ -253,7 +281,7 @@ const makeAreaChart = (data) => { ...@@ -253,7 +281,7 @@ const makeAreaChart = (data) => {
count: 1 count: 1
} }
var areaValueAxis = areaChart.yAxes.push(new am4charts.ValueAxis()); let areaValueAxis = areaChart.yAxes.push(new am4charts.ValueAxis());
areaValueAxis.tooltip.disabled = true; areaValueAxis.tooltip.disabled = true;
areaValueAxis.fontSize = 8; areaValueAxis.fontSize = 8;
areaValueAxis.renderer.labels.template.fill = am4core.color(mainTextColor); areaValueAxis.renderer.labels.template.fill = am4core.color(mainTextColor);
...@@ -268,7 +296,7 @@ const makeAreaChart = (data) => { ...@@ -268,7 +296,7 @@ const makeAreaChart = (data) => {
makeDateRange(areaDateAxis, 2, 2, "#595952"); makeDateRange(areaDateAxis, 2, 2, "#595952");
makeDateRange(areaDateAxis, 4, 4, "#838278"); makeDateRange(areaDateAxis, 4, 4, "#838278");
makeDateRange(areaDateAxis, 8, 3, "#B1AE9F"); makeDateRange(areaDateAxis, 8, 3, "#B1AE9F");
makeDateRange(areaDateAxis, 11, 1, "#E1DBC8"); // FIXME: this range shows a small line separator between Dec-Jan makeDateRange(areaDateAxis, 11, 1, "#E1DBC8");
areaChart.cursor = new am4charts.XYCursor(); areaChart.cursor = new am4charts.XYCursor();
areaChart.snapToSeries = areaSeries2; areaChart.snapToSeries = areaSeries2;
...@@ -291,25 +319,17 @@ const makeAreaChart = (data) => { ...@@ -291,25 +319,17 @@ const makeAreaChart = (data) => {
month = parseInt(mm) + 1; month = parseInt(mm) + 1;
month.toString(); month.toString();
} }
let filterDate = new Date(`${yy}-${month}-01T00:00:00`); let filterDate = new Date(`${yy}-${month}`).setUTCHours(6, 0, 0);
// only update chart when dates in cursor change month // only update chart when dates in cursor change month
if (filterDate.valueOf() != previousDate.valueOf()) { if (filterDate.valueOf() != previousDate.valueOf()) {
previousDate = filterDate; previousDate = filterDate;
updateBarChart(filterDate, barChartData); updateBarChart(filterDate, barChartData); // FIXME: when calling this update, bar chart may not exist yet
} }
}) });
} }
am4core.ready(function() { const makeBarChart = (data) => {
let barChart = am4core.create("dimfrcpo-graph", am4charts.XYChart);
// Themes begin
am4core.useTheme(am4themes_animated);
am4core.useTheme(grijalva_theme);
//let mainTextColor = getComputedStyle(document.body).getPropertyValue('--main-text-color');
// Themes end
// bar chart
var barChart = am4core.create("dimfrcpo-graph", am4charts.XYChart);
let barTitle = barChart.titles.create(); let barTitle = barChart.titles.create();
barTitle.text = "Conteo por tipo de cuerpo"; barTitle.text = "Conteo por tipo de cuerpo";
...@@ -317,9 +337,10 @@ am4core.ready(function() { ...@@ -317,9 +337,10 @@ am4core.ready(function() {
barTitle.marginBottom = 5; barTitle.marginBottom = 5;
barTitle.fill = am4core.color(mainTextColor); barTitle.fill = am4core.color(mainTextColor);
barChart.data = data;
// Create axes // Create axes
//var barCategoryAxis = barChart.yAxes.push(new am4charts.CategoryAxis()); let barCategoryAxis = barChart.xAxes.push(new am4charts.CategoryAxis());
var barCategoryAxis = barChart.xAxes.push(new am4charts.CategoryAxis());
barCategoryAxis.dataFields.category = "grupo"; barCategoryAxis.dataFields.category = "grupo";
barCategoryAxis.numberFormatter.numberFormat = "#,###.#"; barCategoryAxis.numberFormatter.numberFormat = "#,###.#";
barCategoryAxis.renderer.inversed = true; barCategoryAxis.renderer.inversed = true;
...@@ -331,8 +352,7 @@ am4core.ready(function() { ...@@ -331,8 +352,7 @@ am4core.ready(function() {
barCategoryAxis.title.text = "Superficie (Ha)"; barCategoryAxis.title.text = "Superficie (Ha)";
barCategoryAxis.title.fill = am4core.color(mainTextColor); barCategoryAxis.title.fill = am4core.color(mainTextColor);
//var barValueAxis = barChart.xAxes.push(new am4charts.ValueAxis()); let barValueAxis = barChart.yAxes.push(new am4charts.ValueAxis());
var barValueAxis = barChart.yAxes.push(new am4charts.ValueAxis());
//barValueAxis.renderer.opposite = true; //barValueAxis.renderer.opposite = true;
//barValueAxis.calculateTotals = true //barValueAxis.calculateTotals = true
barValueAxis.fontSize = 10; barValueAxis.fontSize = 10;
...@@ -340,42 +360,8 @@ am4core.ready(function() { ...@@ -340,42 +360,8 @@ am4core.ready(function() {
barValueAxis.renderer.labels.template.fill = am4core.color(mainTextColor); barValueAxis.renderer.labels.template.fill = am4core.color(mainTextColor);
barValueAxis.max = 1250; // TODO: compute max value from data barValueAxis.max = 1250; // TODO: compute max value from data
// Create series // crate series
function createSeries(field, name) { makeBarSeries(barChart, "ap", "Agua permanente");
var barSeries = barChart.series.push(new am4charts.ColumnSeries()); makeBarSeries(barChart, "at", "Áreas temporalmente inundadas");
//barSeries.dataFields.valueX = field; makeBarSeries(barChart, "av", "Suelos húmedos-vegetación acuática");
//barSeries.dataFields.categoryY = "grupo"; }
barSeries.dataFields.valueY = field; \ No newline at end of file
barSeries.dataFields.categoryX = "grupo";
//barSeries.dataFields.valueYShow = "count";
//barSeries.dataFields.categoryY = "grupo"; //"year";
barSeries.dataFields.categoryX = "grupo"; //"year";
barSeries.name = name;
barSeries.columns.template.tooltipText = "[underline][bold]Menor a [bold]{categoryX.formatNumber('#,###.#')} Ha[/]: {valueY.formatNumber('#,###.#')} cuerpos[/]";
barSeries.columns.template.height = am4core.percent(100);
barSeries.sequencedInterpolation = true;
var barValueLabel = barSeries.bullets.push(new am4charts.LabelBullet());
//barValueLabel.label.text = "{valueX}";
barValueLabel.label.text = "{valueY}";
barValueLabel.label.horizontalCenter = "middle";
//barValueLabel.label.verticalCenter = "top";
//barValueLabel.label.align = "center";
barValueLabel.label.dx = 3;
barValueLabel.label.dy = -5;
barValueLabel.label.hideOversized = false;
barValueLabel.label.truncate = false;
barValueLabel.fontSize = 10;
//barValueLabel.label.fill = am4core.color(mainTextColor);
barValueLabel.label.fill = am4core.color("#fff");
}
createSeries("ap", "Agua permanente");
createSeries("at", "Áreas temporalmente inundadas");
createSeries("av", "Suelos húmedos-vegetación acuática");
}); // end am4core.ready()
//--------------------------------------------------------------------------------------------------------------------
\ No newline at end of file
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
* January 2021 * January 2021
*/ */
/* globals omnivore, Promise, makeBaseMap, am4core, makeRadialChart, makeLineChart, makeAreaChart */ /* globals omnivore, Promise, makeBaseMap, am4core, makeRadialChart, makeLineChart, makeAreaChart, makeBarChart */
/* exported. userFiles, userDates, timeParse, layerControl, yearList */ /* exported. userFiles, userDates, timeParse, layerControl, yearList */
let timeParse, let timeParse,
...@@ -267,9 +267,9 @@ const setupMap = (dates) => { ...@@ -267,9 +267,9 @@ const setupMap = (dates) => {
}); });
const offsetGlobal = (center, zoom, refMap, tgtMap) => { const offsetGlobal = (center, zoom, refMap, tgtMap) => {
var refC = refMap.getContainer(); let refC = refMap.getContainer();
var tgtC = tgtMap.getContainer(); let tgtC = tgtMap.getContainer();
var pt = refMap.project(center, zoom) let pt = refMap.project(center, zoom)
.subtract([refC.offsetLeft, refC.offsetTop]) .subtract([refC.offsetLeft, refC.offsetTop])
.subtract(refMap.getSize().divideBy(2)) .subtract(refMap.getSize().divideBy(2))
.add([tgtC.offsetLeft, tgtC.offsetTop]) .add([tgtC.offsetLeft, tgtC.offsetTop])
...@@ -309,7 +309,7 @@ const populateMap = async(mapData) => { ...@@ -309,7 +309,7 @@ const populateMap = async(mapData) => {
// wait for all queries to complete and then set chart data // wait for all queries to complete and then set chart data
Promise.all(queries).then( data => { Promise.all(queries).then( data => {
// TODO: maybe make this a function so it can be used to update chart when changing dates // TODO: maybe make this a function so it can be used to update chart when changing dates
let chartData = []; let radialChartData = [];
monthArray.forEach( (month, index) => { monthArray.forEach( (month, index) => {
let element = {}; let element = {};
yearList.forEach( year => { yearList.forEach( year => {
...@@ -318,9 +318,9 @@ const populateMap = async(mapData) => { ...@@ -318,9 +318,9 @@ const populateMap = async(mapData) => {
let yearData = data.filter(d => new Date(d.date).getMonth() == index && new Date(d.date).getFullYear() == year); let yearData = data.filter(d => new Date(d.date).getMonth() == index && new Date(d.date).getFullYear() == year);
element[year] = yearData.length > 0 ? yearData[0].area : null; element[year] = yearData.length > 0 ? yearData[0].area : null;
}); });
chartData.push(element); radialChartData.push(element);
}); });
makeRadialChart(chartData, monthArray, yearList); makeRadialChart(radialChartData, monthArray, yearList);
}); });
// LINE + STACKED AREA CHARTS // LINE + STACKED AREA CHARTS
...@@ -363,13 +363,13 @@ const populateMap = async(mapData) => { ...@@ -363,13 +363,13 @@ const populateMap = async(mapData) => {
makeAreaChart(chartData); makeAreaChart(chartData);
}); });
// populate bars // // BAR CHART
// async queries for each date that has been loaded // async queries for each date that has been loaded
const queries_pb = userFiles.map(async(mes, i) => { const queries_pb = userFiles.map(async(mes, i) => {
let query_pb = `${baseUrl}/query/${mes}?columns=descrip, areacpo`; let query_pb = `${baseUrl}/query/${mes}?columns=descrip, areacpo`;
const queryData = await d3.json(query_pb); const queryData = await d3.json(query_pb);
let date = new Date(dateArray[i]); let date = new Date(userDates[i]);
for (let k = 0; k < queryData.length; k++) { for (let k = 0; k < queryData.length; k++) {
queryData[k].date = date; // assign date to each element queryData[k].date = date; // assign date to each element
// assign bar groups to each element // assign bar groups to each element
...@@ -385,9 +385,9 @@ const populateMap = async(mapData) => { ...@@ -385,9 +385,9 @@ const populateMap = async(mapData) => {
// wait for all queries to complete and set barChartData to its response // wait for all queries to complete and set barChartData to its response
Promise.all(queries_pb).then((d) => { Promise.all(queries_pb).then((d) => {
barChartData = [].concat.apply([], d); barChartData = [].concat.apply([], d);
// set initial date to january 2016 // set initial date to january 2016
let filterDate = new Date(dateArray[0]); let filterDate = new Date(userDates[0]);
makeBarChart(barChartData);
updateBarChart(filterDate, barChartData); updateBarChart(filterDate, barChartData);
}); });
...@@ -492,7 +492,7 @@ const populateMap = async(mapData) => { ...@@ -492,7 +492,7 @@ const populateMap = async(mapData) => {
"Carto Light": cartoLightLayer, "Carto Light": cartoLightLayer,
"OpenStreetMap": osmLayer "OpenStreetMap": osmLayer
}; };
var overlays = { let overlays = {
"<span id=\"cuencaOverlay\">Agua en la cuenca del Grijalva</span>": timeLayer "<span id=\"cuencaOverlay\">Agua en la cuenca del Grijalva</span>": timeLayer
}; };
...@@ -638,7 +638,7 @@ L.TimeDimension.Layer.Tile = L.TimeDimension.Layer.extend({ ...@@ -638,7 +638,7 @@ L.TimeDimension.Layer.Tile = L.TimeDimension.Layer.extend({
return; return;
} }
var time = this._timeDimension.getCurrentTime(); let time = this._timeDimension.getCurrentTime();
// get data for time // get data for time
let d = new Date(time), let d = new Date(time),
...@@ -671,7 +671,7 @@ let legend = L.control({ ...@@ -671,7 +671,7 @@ let legend = L.control({
legend.onAdd = () => { legend.onAdd = () => {
let div = L.DomUtil.create("div", "info legend leaflet-bar"); let div = L.DomUtil.create("div", "info legend leaflet-bar");
var html = "<h6>Cuerpos de agua</h6><ul>"; let html = "<h6>Cuerpos de agua</h6><ul>";
Object.keys(colors).forEach( c => { Object.keys(colors).forEach( c => {
html += `<li><i style="background: ${colors[c].fill}"></i>${c}</li>`; html += `<li><i style="background: ${colors[c].fill}"></i>${c}</li>`;
}); });
...@@ -683,8 +683,7 @@ legend.onAdd = () => { ...@@ -683,8 +683,7 @@ legend.onAdd = () => {
const updateBarChart = (filterDate, data) => { const updateBarChart = (filterDate, data) => {
let popBarsChart = am4core.registry.baseSprites.find(c => c.htmlContainer.id === "dimfrcpo-graph"); let popBarsChart = am4core.registry.baseSprites.find(c => c.htmlContainer.id === "dimfrcpo-graph");
let areclass = data.filter(d => d.date.valueOf() == filterDate.valueOf()); let areclass = data.filter(d => d.date.valueOf() == filterDate.valueOf());
let elementpb = {},
var elementpb = {},
cart_pb = []; cart_pb = [];
// TODO: prepare all these group data sets instead of recalculating when calling the function // TODO: prepare all these group data sets instead of recalculating when calling the function
...@@ -700,7 +699,8 @@ const updateBarChart = (filterDate, data) => { ...@@ -700,7 +699,8 @@ const updateBarChart = (filterDate, data) => {
let cart_pb1 = cart_pb.filter(function(d) { return d.ap > 0 || d.at > 0 || d.av > 0 }); let cart_pb1 = cart_pb.filter(function(d) { return d.ap > 0 || d.at > 0 || d.av > 0 });
cart_pb1.sort((a, b) => (a < b ? 1 : -1)); cart_pb1.sort((a, b) => (a < b ? 1 : -1));
//console.log("cart_pb1", cart_pb1); if (popBarsChart) {
popBarsChart.data = cart_pb1; popBarsChart.data = cart_pb1;
popBarsChart.invalidateRawData(); popBarsChart.invalidateRawData();
}
} }
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment