Echarts柱状图设置渐变色

一、前言

本文针对react,在react项目中使用echarts

二、前期准备

安装依赖 npm i echarts --save

三、代码注释以及效果

案例一:
import React, { useEffect, useRef } from 'react'
// 引入echarts包
import * as echarts from "echarts"

function App() {
  // 获得实例dom
  const dom = useRef();
  // 配置项
  const option = {
    title: {
      text: 'Echarts 渐变色'
    },
    xAxis: {
      data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
    },
    yAxis: {},
    series: [
      {
        name: '销量',
        type: 'bar',
        data: [5, 20, 36, 10, 10, 20],
        // 设置渐变色
        itemStyle: {
          normal: {
            color: function (params) {
              return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "red" },
                { offset: 1, color: "purple" }
              ], false)
            }
          }
        }
      }
    ]
  }
  
  useEffect(() => {
  	// 初始化图例
    const chart = echarts.init(dom.current)
    // 在图例中加入配置项
    chart.setOption(option)
  }, [])

  return (
    <div className="App">
      // 一定要设置dom大小
      <div ref={dom} style={{ width: 500, height: 500 }}></div>
    </div>
  );
}

export default App;

在这里插入图片描述

案例二:
import React, { useEffect, useRef } from 'react'
import * as echarts from "echarts"

function App() {
  // 获得实例dom
  const dom = useRef();
  // 配置项
  const option = {
    title: {
      text: 'Echarts 渐变色Ⅱ'
    },
    xAxis: {},
  	yAxis: {},
    dataset: {
      // 前面两位 第一根柱子的坐标 后面两位 第二根柱子的左边
      source: [[1, 0.5, 1, 1], [2, 2, 2, 1.5], [3, 3, 3, 4]]
    },
    series: [
      {
        type: 'bar',
        // 设置渐变色 第一条柱子
        itemStyle: {
          normal: {
            color: function (params) {
              return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "red" },
                { offset: 1, color: "purple" }
              ], false)
            }
          }
        }
      }, {
        type: 'bar',
        // 设置渐变色 第二条柱子
        itemStyle: {
          normal: {
            color: function (params) {
              return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "blue" },
                { offset: 1, color: "purple" }
              ], false)
            }
          }
        }
      }
    ]
  }
  
  useEffect(() => {
    const chart = echarts.init(dom.current)
    chart.setOption(option)
  }, [])

  return (
    <div className="App">
    // 一定要设置dom大小
      <div ref={dom} style={{ width: 500, height: 500 }}></div>
    </div>
  );
}

export default App;

在这里插入图片描述

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值