echarts 饼图中间添加文字

需求:饼图中间展示总量数据

方法一、设置series对应饼图的label属性

javascript 复制代码
series: [{
  type: "pie",
  radius: ['55%', '62%'],
  center: ["67%", "50%"],
  itemStyle: {
    borderRadius: 10,
    borderColor: '#fff',
    borderWidth: 2
  },
  // 主要代码在这里
  label: {
    normal: {
      show: true,
      position: 'center', // 展示在中间位置
      formatter:() => {
        return `{a|数据量}\n\n{${String(total[0]).length < 10 ? 'bM' : 'bS'}|${total[2]}GB}`
      },
      rich: {
        a: {
          color: '#111928',
          fontSize: 16,
          fontWeight: 900,
        },
        bM: {
          fontSize: 16,
          fontWeight: 700,
          color: '#6B7280'
        },
        bS: {
          fontSize: 12,
          fontWeight: 700,
          color: '#6B7280'
        },
      },
    },
  },
  labelLine: {
    length: 10,
    length2: 30,
    minTurnAngle: 135,
    lineStyle: {
      type: 'dashed',
      width: 0.5,
    }
  },
  encode: {
    itemName: "product",
    value: "数据量",
  },
}]

但这种方法会把"饼图扇区外侧,通过视觉引导线连到相应的扇区"的label覆盖掉,以至于显示不了。如下图:

方法二、基于上一个方法做优化,为series再设置一个相同位置的饼图

javascript 复制代码
series: [{
  type: "pie",
  radius: ['55%', '62%'],
  center: ["67%", "50%"],
  itemStyle: {
    borderRadius: 10,
    borderColor: '#fff',
    borderWidth: 2
  },
  // 真正的饼图就不动label的默认配置了
  // 下面是为视觉引导线做配置
  labelLine: {
    length: 10,
    length2: 30,
    minTurnAngle: 135,
    lineStyle: {
      type: 'dashed',
      width: 0.5,
    }
  },
  encode: {
    itemName: "product",
    value: "数据量",
  },
},
// 下面这个饼图是为了中间字写的
{
  type: 'pie',
  radius: ['0%', '0%'],
  center: ["67%", "50%"], // 这个要与真正的饼图写一样的位置
  emphasis:{
    disabled: true, // 是否关闭高亮状态
  },
  tooltip: {
    show: false // 是否展示提示框浮层
  },
  // 这里与方法一的label设置的一样
  label: {
    normal: {
      show: true,
      position: 'center',
      formatter:() => {
        return `{a|数据量}\n\n{${String(total[0]).length < 10 ? 'bM' : 'bS'}|${total[2]}GB}`
      },
      rich: {
        a: {
          color: '#111928',
          fontSize: 16,
          fontWeight: 900,
        },
        bM: {
          fontSize: 16,
          fontWeight: 700,
          color: '#6B7280'
        },
        bS: {
          fontSize: 12,
          fontWeight: 700,
          color: '#6B7280'
        },
      },
    },
  },
}]

另外,大家应该也可以用title的配置,修改放置位置来展示中间字;当然,也会有相同的问题,如果需求需要正常的title展示,就可以借鉴方法二,画一个相同位置且不展示的饼图实现它。

大家要是遇到更优的方法,欢迎评论~

相关推荐
云水一下6 小时前
从零开始!VMware安装Fedora Workstation 44桌面系统完整教程
前端
小码哥_常7 小时前
安卓黑科技:实现多平台商品详情页一键跳转APP
前端
killerbasd8 小时前
还是迷茫 5.3
前端·react.js·前端框架
不会敲代码18 小时前
TCP/IP 与前端性能:从数据包到首次渲染的底层逻辑
前端·tcp/ip
kyriewen9 小时前
奥特曼借GPT-5.5干杯,而你的Copilot正按Token收钱
前端·github·openai
AC赳赳老秦9 小时前
投标合规提效:用 OpenClaw 实现标书 / 合同自动审核、关键词校验、格式优化,降低废标风险
开发语言·前端·python·eclipse·emacs·deepseek·openclaw
kyriewen9 小时前
代码写成一锅粥?3个设计模式让你的项目“起死回生”
前端·javascript·设计模式
不会敲代码19 小时前
从零搭建 AI 日记助手:用 Milvus 向量数据库实现语义搜索
javascript·openai
千寻girling9 小时前
《 Git 详细教程 》
前端·后端·面试
threelab10 小时前
Three.js UV 图像变换效果 | 三维可视化 / AI 提示词
javascript·人工智能·uv