插件窝 干货文章 uChart如何实现类似ECharts的堆叠柱状图数据对比效果?

uChart如何实现类似ECharts的堆叠柱状图数据对比效果?

stack 堆叠 柱状 javascript 177    来源:    2025-03-25

在uChart中实现类似ECharts的堆叠柱状图数据对比效果

uChart作为一款轻量级的图表库,虽然功能不如ECharts全面,但仍然可以实现堆叠柱状图的数据对比效果。以下是实现方法:

基本实现步骤

  1. 准备数据格式

    const series = [
     {
       name: '系列1',
       data: [120, 132, 101, 134, 90, 230, 210],
       stack: 'stack1'  // 关键属性,相同stack值的系列会堆叠
     },
     {
       name: '系列2',
       data: [220, 182, 191, 234, 290, 330, 310],
       stack: 'stack1'  // 与系列1相同的stack值
     },
     {
       name: '系列3',
       data: [150, 232, 201, 154, 190, 330, 410],
       stack: 'stack2'  // 不同的stack值会形成新的堆叠组
     }
    ];
    
  2. 配置图表选项

    const options = {
     type: 'column',
     categories: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
     series: series,
     yAxis: {
       format: (val) => val.toFixed(0)
     },
     extra: {
       column: {
         type: 'stack'  // 启用堆叠模式
       }
     }
    };
    
  3. 渲染图表

    const chart = new uCharts(options);
    chart.render('canvasId');
    

高级配置选项

  1. 自定义颜色

    series: [
     {
       name: '系列1',
       data: [120, 132, 101, 134, 90, 230, 210],
       stack: 'stack1',
       color: '#1890FF'
     },
     // 其他系列...
    ]
    
  2. 添加图例

    extra: {
     column: {
       type: 'stack'
     },
     legend: {
       show: true,
       position: 'top',
       float: 'center'
     }
    }
    
  3. 设置数据标签

    extra: {
     column: {
       type: 'stack',
       barWidth: 30,
       labelShow: true,
       format: (val) => val.toFixed(0)
     }
    }
    

与ECharts的主要差异

  1. 功能差异

    • uChart的堆叠功能相对简单,不支持ECharts中的百分比堆叠
    • 动画效果和交互功能较ECharts弱
  2. 性能优势

    • uChart更轻量,在小程序等环境中性能更好
    • 包体积更小,适合对体积敏感的场景

完整示例代码

const options = {
  type: 'column',
  categories: ['1月', '2月', '3月', '4月', '5月', '6月'],
  series: [
    {
      name: '产品A',
      data: [35, 36, 31, 33, 13, 34],
      stack: 'total',
      color: '#1890FF'
    },
    {
      name: '产品B',
      data: [18, 27, 21, 24, 6, 28],
      stack: 'total',
      color: '#2FC25B'
    },
    {
      name: '产品C',
      data: [18, 27, 21, 24, 6, 28],
      stack: 'total2',
      color: '#FACC14'
    }
  ],
  yAxis: {
    gridType: 'dash',
    dashLength: 2,
    format: (val) => val.toFixed(0) + 'k'
  },
  extra: {
    column: {
      type: 'stack',
      barWidth: 20,
      labelShow: true
    },
    legend: {
      show: true,
      position: 'top',
      float: 'center'
    },
    tooltip: {
      showBox: true
    }
  }
};

const chart = new uCharts(options);
chart.render('canvasId');

通过以上配置,您可以在uChart中实现类似ECharts的堆叠柱状图效果,用于数据对比分析。