echarts 饼图中间添加文字

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

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

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再设置一个相同位置的饼图

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展示,就可以借鉴方法二,画一个相同位置且不展示的饼图实现它。

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

猜你喜欢

转载自blog.csdn.net/qq_58340302/article/details/131949351