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

amCharts 5折线图Tooltip不显示及自定义数据异常问题

问题解决:amCharts5折线图添加自定义Tooltip后消失+仅显示X轴数值

问题根源

你的代码存在两个核心问题:

  • 数据是倒序排列(从最新日期到最旧),虽不会直接导致折线消失,但会引发视觉异常;
  • X轴和系列同时设置了Tooltip,可能触发交互冲突,且你需要的是系列Tooltip仅显示X轴数值,X轴的Tooltip属于冗余配置。

修复步骤

  1. 调整数据顺序:将数据按时间戳升序排列(从旧到新),确保折线正常渲染;
  2. 移除X轴的Tooltip设置:无需给X轴单独添加Tooltip,专注配置系列的Tooltip;
  3. 修改系列Tooltip内容:将labelText改为仅显示格式化后的X轴日期,利用已配置的dateFormatter自动处理时间戳格式。

完整修复代码

var root = am5.Root.new("chartdiv");
root.dateFormatter.setAll({
  dateFormat: "MMM, yyyy",
  dateFields: ["valueX"]
});
root.setThemes([am5themes_Animated.new(root)]);

var chart = root.container.children.push(am5xy.XYChart.new(root, {}));
var cursor = chart.set(
  "cursor",
  am5xy.XYCursor.new(root, {
    behavior: "none"
  })
);
cursor.lineY.set("visible", false);

// 调整为升序排列的数据(从旧到新)
var data = [
  { date: 1667691283000, ajf: 263.18, topix: 180.49 },
  { date: 1670283283000, ajf: 252.86, topix: 172.25 },
  { date: 1672961683000, ajf: 265.45, topix: 179.87 },
  { date: 1675640083000, ajf: 276.12, topix: 181.57 },
  { date: 1678059283000, ajf: 278.21, topix: 184.66 },
  { date: 1680737683000, ajf: 288.02, topix: 189.64 }
];

// 创建坐标轴 - 移除X轴的tooltip设置
var xAxis = chart.xAxes.push(
  am5xy.DateAxis.new(root, {
    baseInterval: { timeUnit: "month", count: 1 },
    renderer: am5xy.AxisRendererX.new(root, {})
  })
);

var yAxis = chart.yAxes.push(
  am5xy.ValueAxis.new(root, {
    renderer: am5xy.AxisRendererY.new(root, {})
  })
);

// 添加系列 - 修改Tooltip仅显示X轴数值
var series = chart.series.push(
  am5xy.LineSeries.new(root, {
    xAxis: xAxis,
    yAxis: yAxis,
    valueYField: "ajf",
    valueXField: "date",
    tooltip: am5.Tooltip.new(root, {
      labelText: "{valueX}" // 仅显示格式化后的X轴日期
    })
  })
);

series.strokes.template.setAll({
  strokeWidth: 2
});

series.data.setAll(data);

series.appear(1000);
chart.appear(1000, 100);

关键说明

  • 数据升序排列后,折线会按时间顺序从左到右正常绘制;
  • 移除X轴的Tooltip避免了交互冲突,让系列Tooltip专注显示目标内容;
  • 你之前配置的dateFormatter会自动将valueX(时间戳)格式化为MMM, yyyy样式,无需额外处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 15:50:19