跳转到内容

横向柱状图参数数量设置

刀刀
0字
0分钟
2026/8/16

UI 图需要实现一个横向柱状图,柱状图有两个数据,一个总数、一个超限数据,且在柱体右上方还要显示其数值。效果:

效果

在 ECharts 官网中,是没有这些相关的案例参考的代码和图例,但是可以在民间第三方社区中寻找别人做好的效果来参考,地址为 makeapie echarts社区图表可视化案例

实现该效果,可通过拆分来依次实现:

  1. 实现横向柱状图的渲染,柱状图为重叠的多柱体,且不需要渲染 y 轴的线
  2. 鼠标悬停显示文本自定义
  3. 在柱体右上方显示数据

Echart 横向柱状图柱体基础渲染

实现第一点,一个横向柱状图,样式都为圆角柱体,且背景柱体颜色为灰色,内容柱体为渐变颜色。

圆角样式通过为 series 数组内对应对象的 itemStyle 属性中设置 barBorderRadius 即可,颜色在itemStyle 属性中设置 color 即可。实现渐变颜色,color 修改为一个对象,通过 colorStops 数组设置,其中 offset 为临界值,color 为要设置的渐变颜色。

y 轴不显示竖线,则需要在 yAxis 数组对象中设置 axisLineaxisTicksplitLine 三个对象即可,每个对象都是添加一个 show 属性为 false

代码:

js
var option = {
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'none',
    },
  },
  xAxis: {
    show: false,
    type: 'value',
  },
  // y轴坐标,不显示对应的竖线
  yAxis: [
    {
      type: 'category',
      inverse: true,
      axisLabel: {
        show: true,
        textStyle: {
          color: '#aaa',
        },
      },
      splitLine: {
        show: false,
      },
      axisTick: {
        show: false,
      },
      axisLine: {
        show: false,
      },
      data: ['1', '2', '3'],
    },
  ],
  series: [
    {
      name: '同比增长比例',
      type: 'bar',
      zlevel: 1,
      itemStyle: {
        normal: {
          barBorderRadius: 10,
          // 柱体颜色渐变
          color: {
            type: 'linear',
            colorStops: [
              {
                offset: 0,
                color: 'rgba(218, 255, 242, 0.1)',
              },
              {
                offset: 1,
                color: 'rgb(239, 255, 250)',
              },
            ],
          },
        },
      },
      barWidth: 10,
      emphasis: {
        disabled: true,
        focus: 'none',
      },
      data: [1, 2, 3],
    },
    {
      name: '背景',
      type: 'bar',
      barWidth: 10,
      // barGap: '-100%',
      data: [6, 5, 4],
      emphasis: {
        disabled: true,
        focus: 'none',
      },
      itemStyle: {
        // 设置颜色和圆角
        normal: {
          color: 'rgb(159, 159, 159)',
          barBorderRadius: 10,
        },
      },
    },
  ],
}

Echart 横向柱状图鼠标悬停内容自定义

悬停自定义,即在 tooltip 对象属性中设置 formatter 函数,返回需要显示的字符串内容即可。

Echart 横向柱状图柱体数据显示

接下来处理柱体数据显示。实现数据显示在柱体上方,只需给 series 对应数据对象设置 label ,让其展示,showtrue ,设置 position 定位,color 控制颜色。

重点是设置 offset 偏移量,让其能够偏移到想要的位置去。代码:

js
;[
  {
    // ...
    label: {
      show: true,
      position: 'insideBottomRight',
      distance: 0,
      offset: [0, -15],
      color: '#fff',
    },
  },
]

贡献者

The avatar of contributor named as duyidao duyidao
The avatar of contributor named as v_duyilin v_duyilin
The avatar of contributor named as 刀刀 刀刀
The avatar of contributor named as 平安喜乐 平安喜乐

页面历史

刀刀博客累计访客 人;文档累计访问量共