echarts柱状图——堆叠、多柱堆叠,并在顶部展示总和

  • 实现的效果
    在这里插入图片描述

  • 要求
    1、堆叠数据
    2、可以有多个柱子堆叠
    3、要展示每个堆叠柱子的总和

  • options配置

const xData = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"];
const morningIncome = [1, 2, 3, 4, 5, 6, 7];
const morningPay = [7, 6, 5, 4, 3, 2, 1];
const afternoonIncome = [9, 8, 7, 6, 5, 4, 3];
const afternoonPay = [1, 3, 5, 7, 9, 10, 12];

const options = {
  title: {
    text: "每日开支💰",
  },
  tooltip: {
    trigger: "axis",
    formatter: (params: any) => {
      const allData = params.map((item: any) => item.data);
      let dataStr = `<p style="font-weight:bold;">${params[0].name}</p>`;
      params.forEach((item: any, index: number) => {
        if (index === 0) {
          dataStr += `上午:<span style="color:#000000;">${allData[0] + allData[1]}</span>`;
        }
        dataStr += `<div>
          <div style="margin: 0 8px;">
            <span style="display:inline-block;margin-right:5px;width:10px;height:10px;border-radius:50%;background-color:${item.color};"></span>
            <span>${item.seriesName}</span>
            <span style="color:#000000;">${item.data}</span>
          </div>
        </div>`;
        if (index === 1) {
          dataStr += `<br/>下午:<span style="color:#000000;">${allData[2] + allData[3]}</span>`;
        }
      });
      return dataStr;
    },
  },
  grid: {
    left: "1%",
    right: "1%",
    top: "15%",
    bottom: "1%",
    containLabel: true,
  },
  legend: {},
  xAxis: {
    type: "category",
    data: xData,
  },
  yAxis: {
    type: "value",
  },
  series: [
    {
      name: "收入",
      type: "bar",
      stack: "stack1", // 重点!!stack值相同的会队叠在一起,后面数在前面的上面
      data: morningIncome,
    },
    {
      name: "支出",
      type: "bar",
      stack: "stack1",
      data: morningPay,
      label: {
        show: true,
        position: "top",
        // 巧妙利用lable,计算并展示总值
        formatter: (params: any) =>
          morningIncome[params.dataIndex] + morningPay[params.dataIndex],
      },
    },
    {
      name: "收入",
      type: "bar",
      stack: "stack2",
      data: afternoonIncome,
    },
    {
      name: "支出",
      type: "bar",
      stack: "stack2",
      data: afternoonPay,
      label: {
        show: true,
        position: "top",
        formatter: (params: any) =>
          afternoonIncome[params.dataIndex] + afternoonPay[params.dataIndex],
      },
    },
  ],
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

英子的搬砖日志

您的鼓励是我创作的动力~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值