echars柱状图怎么每个柱子设置不同颜色

需求引出

在有的时候,我们需要给柱状图的每根柱子设置不同的颜色,或者是每几个柱子设置不同的颜色,如下图所示:

方法一

在 series 下 data 同级别中,增加一个 itemStyle 对象的属性,给color 返回一个数组

如下代码所示:

javascript 复制代码
    series: [
      {
        data: [10, 30, 20, 14, 23, 32, 34],
        //设置每个柱子不同的颜色
        itemStyle: {
          color: function (params) {
            // 根据params的
            const colorsMap = [
              '#4FE773',
              'red',
              'blue',
              '#CAC8CA',
              'yellow',
              'pink',
              'rgb(10,58,6)'
            ]
            //返回对应的颜色
            return colorsMap[params.dataIndex]
          }
        },
        type: 'bar',
        showBackground: true,
        color: '#4FE773',
        backgroundStyle: {
          color: 'rgba(180, 180, 180, 0.2)'
        }
      }
    ]

方法二

给 itemStyle 设置 normal 对象,每个柱子的颜色即为colorList数组里的每一项,如果柱子数目多于colorList的长度,则柱子颜色循环使用该数组

代码如下:

javascript 复制代码
        itemStyle: {
          normal: {
            //每个柱子的颜色即为colorList数组里的每一项,如果柱子数目多于colorList的长度,则柱子颜色循环使用该数组
            color: function (params) {
              var colorList = [
                'rgb(164,205,238)',
                'rgb(42,170,227)',
                'rgb(25,46,94)',
                'rgb(195,229,235)'
              ]
              return colorList[params.dataIndex]
            }
          }
        },

每根柱子随机颜色

我们可以使用 Math.random() 根 rgb 的模式随机生成颜色给每一个柱子

代码如下:

javascript 复制代码
        itemStyle: {
          color: function () {
            return (
              '#' +
              Math.floor(Math.random() * (256 * 256 * 256 - 1)).toString(16)
            )
          }
        },
相关推荐
小徐_23331 天前
uni-app vue3 也能使用 Echarts?Wot Starter 是这样做的!
前端·uni-app·echarts
java水泥工2 天前
基于Echarts+HTML5可视化数据大屏展示-白茶大数据溯源平台V2
大数据·echarts·html5
蜚鸣2 天前
Vue的快速入门
vue
码上暴富3 天前
Echarts雷达图根据数值确定颜色
前端·javascript·echarts
吃饭最爱3 天前
⽹络请求Axios的概念和作用
vue
懒大王95273 天前
uni-app + Vue3 开发展示 echarts 图表
前端·uni-app·echarts
魂尾ac3 天前
Django + Vue3 前后端分离技术实现自动化测试平台从零到有系列 <第一章> 之 注册登录实现
后端·python·django·vue
是罐装可乐4 天前
深入理解 Vue3 Router:三种路由模式的工作原理与实战应用
架构·vue·路由·history·hash·ssr·router
老华带你飞4 天前
租房平台|租房管理平台小程序系统|基于java的租房系统 设计与实现(源码+数据库+文档)
java·数据库·小程序·vue·论文·毕设·租房系统管理平台
zhz52144 天前
Spring Boot + Redis 缓存性能优化实战:从5秒到毫秒级的性能提升
java·spring boot·redis·缓存·vue