You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AmCharts5+Angular中scrollbarX无数据显示问题求助

问题:AMCharts 5 折线图X轴滚动条为空

尝试创建带xscrollbar的折线图,预期显示正常的X轴滚动条,但实际滚动条为空。

预期效果

预期X轴滚动条效果

实际效果

空的X轴滚动条


问题根源

滚动条的X轴使用了DateAxis,但数据源中的year字段是字符串类型(如"2021"),而DateAxis仅识别日期格式数据(时间戳或Date对象),无法解析字符串年份,导致滚动条无数据渲染。同时主图表X轴为CategoryAxis,与滚动条轴类型不匹配,进一步加剧了数据适配问题。


修复方案

方案1:滚动条X轴改为CategoryAxis(与主图表统一)

无需修改数据格式,将滚动条X轴替换为和主图表一致的CategoryAxis:

// 替换原滚动条X轴代码
const sbXaxis = scrollbarX.chart.xAxes.push(
  am5xy.CategoryAxis.new(root, {
    categoryField: 'year',
    renderer: am5xy.AxisRendererX.new(root, {
      opposite: false,
      strokeOpacity: 0,
    }),
  })
);

方案2:转换数据格式适配DateAxis

若坚持使用DateAxis,需调整数据和轴配置:

  1. 预处理数据,将year转为Date对象:
const data: DataProps[] = [
  {
    year: new Date(2021, 0, 1),
    europe: 5,
    namerica: 2.5,
    asia: 1,
  },
  {
    year: new Date(2022, 0, 1),
    europe: 2.6,
    namerica: 6.7,
    asia: 2.2,
  },
  {
    year: new Date(2023, 0, 1),
    europe: 4.8,
    namerica: 1.9,
    asia: 4.4,
  },
];
  1. 主图表X轴改为DateAxis:
const xAxis = chart.xAxes.push(
  am5xy.DateAxis.new(root, {
    maxDeviation: 0.2,
    baseInterval: { timeUnit: 'year', count: 1 },
    renderer: am5xy.AxisRendererX.new(root, {}),
  })
);
  1. 系列配置中替换categoryXField为dateXField:
// 主图表系列
const series = chart.series.push(
  am5xy.LineSeries.new(root, {
    name: name,
    xAxis: xAxis,
    yAxis: yAxis,
    valueYField: field,
    dateXField: 'year',
    stacked: true,
  })
);

// 滚动条系列
const sbSeries = scrollbarX.chart.series.push(
  am5xy.LineSeries.new(root, {
    name: name,
    xAxis: sbXaxis,
    yAxis: sbYaxis,
    valueYField: field,
    dateXField: 'year',
    stacked: false,
  })
);

额外优化

  • 组件销毁方法名错误,需将OnDestroy改为ngOnDestroy,同时初始化graphRoot变量确保销毁时能正确清理图表:
ngAfterViewInit() {
  this.browserOnly(() => {
    this.graphRoot = am5.Root.new('chartdiv'); // 替换const root = ...
    // ...其他代码
  });
}

ngOnDestroy() {
  this.browserOnly(() => {
    if (this.graphRoot) {
      this.graphRoot.dispose();
    }
  });
}

内容的提问来源于stack exchange,提问作者3gwebtrain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 12:40:28