amCharts 5: CategoryAxis.height() after first datavalidated event

Viewed 126

Context

I am trying to replicate amCharts 4 Auto-adjusting chart height based on a number of data items with amCharts 5 instead.

Code pens with console logs:

The very first time the callback for the datavalidated event of a CategoryAxis is executed, CategoryAxis.height() returns a value that seems wrong. I don't know if the axis was actually rendered before the first datavalidated event. If it was not, then I guess it does not make sense to call CategoryAxis.height().

For information, the very first time the callback is executed, the property inited is false.

Question

The very first time the callback for the datavalidated event of a CategoryAxis is executed, what is CategoryAxis.height() supposed to return?

1 Answers

amCharts have updated their tutorial now for version 5.

amCharts 5: Auto-adjusting chart height based on a number of data items

Now the height is set using

chart.root.dom.style.height = chartHeight + "px";

Some points to note is

amCharts 5 uses "root element" approach - you create a root element, then add actual chart or series objects to it.

...

amCharts 4 did not have a root element, so chart instance was the top element in the tree.

...

amCharts 5 uses Canvas API as its method of rendering, whereas amCharts 4 used SVG.

~ AmCharts 4 and 5

The full code is in their codepen... now the datavalidated event is on the series.

var cellSize = 30;
series.events.on("datavalidated", function(ev) {

  var series = ev.target;
  var chart = series.chart;
  var xAxis = chart.xAxes.getIndex(0);

  // Calculate how we need to adjust chart height
  var chartHeight = series.data.length * cellSize + xAxis.height() + 
  chart.get("paddingTop", 0) + chart.get("paddingBottom", 0);

  // Set it on chart's container
  chart.root.dom.style.height = chartHeight + "px";
});
Related