amCharts 5:根据大量数据项自动调整图表高度

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

我正在尝试用 amCharts 5 复制 amCharts 4 Auto-adjusting chart height based on a number of data items

我已经在 Stack Overflow 上问了 question 以了解 amCharts 5 returns 尚未绘制的轴的高度。暂时没有答案。

到目前为止我最好的是:

// Note: before first render, axis.height() returns erroneous value so the following hack fixes the problem but it assumes an initial root height of 300px
function getAxisHeight(axis: am5xy.CategoryAxis<am5xy.AxisRendererY>) {
  let height = 198.2;

  if (axis.inited) {
    height = axis.height();
  }

  return height;
}

function addAutoHeight(
  root: am5.Root,
  categoryAxis: am5xy.CategoryAxis<am5xy.AxisRendererY>,
  columnSize: number
) {
  categoryAxis.events.on("datavalidated", function (ev) {
    const axis = ev.target;

    const totalColumnSize = axis.data.length * columnSize;
    const adjustHeight = totalColumnSize - getAxisHeight(axis);
    const targetHeight = root.height() + adjustHeight;

    root.dom.style.height = targetHeight + "px";
  });
}

那么,我们能否使用 amCharts 5 根据大量数据项自动调整图表高度,而无需像上面那样进行肮脏的黑客攻击?如果是,什么设置、事件处理程序……允许这样做?

借助新的 amCharts 5 Auto-adjusting chart height based on a number of data items 教程,这对我有用:

function addAutoHeight(
  categoryAxis: am5xy.CategoryAxis<am5xy.AxisRendererY>,
  columnSize: number
) {
  categoryAxis.events.on("datavalidated", function (ev) {
    const yAxis = ev.target;
    const chart = yAxis.chart;

    if (chart) {
      // a title was added on top of the chart
      const titleHeight = chart.children.getIndex(0)?.height() ?? 0;

      const height =
        chart.get("paddingTop", 0) +
        titleHeight +
        chart.topAxesContainer.height() +
        yAxis.data.length * columnSize +
        chart.bottomAxesContainer.height() +
        chart.get("paddingBottom", 0);

      chart.root.dom.style.height = height + "px";
    }
  });
}

事件附加到轴而不是系列,因为只有轴中的值才重要。