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

如何在Syncfusion Flutter Charts实现按年、月、日分组的X轴?

用Syncfusion Flutter Charts实现日期分组X轴+同日期多数据独立柱状图

完全可以用Syncfusion实现你要的效果,不用换库,具体步骤如下:

1. 换用DateTimeAxis替代CategoryAxis

别再用CategoryAxis了,DateTimeAxis是专门处理日期数据的轴,原生支持按年、月、日的层级分组显示,正好匹配你的需求。

2. 配置多级分组标签

通过enableMultiLevelLabels和multiLevelLabelFormatter来实现年月的分组标题,同时设置底层按天间隔,确保同日期的不同数据点能分开:

primaryXAxis: DateTimeAxis(
  intervalType: DateTimeIntervalType.days,
  dateFormat: DateFormat('dd'), // 底部显示日期
  enableMultiLevelLabels: true,
  multiLevelLabelFormatter: (args) {
    final date = DateTime.parse(args.value);
    // 当月第一天时显示年月作为分组标签
    if (date.day == 1) {
      return MultiLevelLabel(
        text: DateFormat('yyyy年MM月').format(date),
        textStyle: TextStyle(fontWeight: FontWeight.w600, fontSize: 12),
      );
    }
    // 如果需要年份分组,可以再加判断date.month == 1时显示年份
    return null;
  },
),

3. 确保同日期多数据显示独立柱状

因为每个数据点的时间是精确到时分秒的,DateTimeAxis会自动识别为不同的X轴位置,所以柱子会独立显示。如果想让同日期的柱子更紧凑,调整系列的间距参数:

ColumnSeries<MedicalTest, DateTime>(
  dataSource: medicalData,
  xValueMapper: (test, _) => DateTime.parse(test.date),
  yValueMapper: (test, _) => test.value,
  groupPadding: 0.2, // 组内柱子间距(同日期的柱子间)
  spacing: 0.1, // 不同日期组的间距
),

4. 数据排序(必要步骤)

先把数据源按日期排序,确保X轴的日期顺序正确:

medicalData.sort((a, b) => DateTime.parse(a.date).compareTo(DateTime.parse(b.date)));

备选库

如果实在不想用Syncfusion,fl_chart也能实现类似效果,但需要手动处理日期分组的标签绘制,逻辑会更繁琐,需要自定义轴的绘制回调。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 07:05:30