Vue3 ECharts 双柱状图渐变色的实现

164 阅读1分钟

话不多说咱们直接上最终效果图

Snipaste_2024-07-23_15-33-36.png

代码实现

{
  // 图例偏移量
  grid: { 
    top: "20%",
    bottom: "16%",
    left: "14%",
    right: "12%"
  },
  // 鼠标悬停显示内容
  tooltip: {  
    axisPointer: {
      type: "none",
      show: false
    },
    trigger: "axis",
    color: "#fff",
    backgroundColor: "rgba(0,0,0,.5)", // 自定义背景颜色
    fontSize: 14,
    borderColor: "rgba(255, 255, 255, .16)", // 自定义边框颜色
    textStyle: {
      color: "#fff", // 自定义文字颜色
      fontSize: 14 // 自定义文字大小
    },
    // 自定义内容 (设置自义定颜色圆点)
    formatter: function(params: any) {
      const res = `
			<div>${params[0].name}</div>
      <div><span style="display:inline-block;margin-right:5px;border-radius:100px;width:10px;height:10px;background-color:#83E76B73"></span>产量:<span style="color: #09ffd2;font-weight: bold;">${params[0].data}</span> KG</div>\n
      <div><span style="display:inline-block;margin-right:5px;border-radius:100px;width:10px;height:10px;background-color:#408CF173"></span>产值:<span style="color: #09ffd2;font-weight: bold;">${params[1].data}</span> 万元</div>
		`;
      return res;
    }
  },
  // 数据源
  series: [
    {
      name: "产量",
      type: "bar",
      yAxisIndex: 0, // 使用第一个Y轴
      barWidth: "14px", // 柱状图大小
      data: [],
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
          {
            //代表渐变色从正上方开始
            offset: 0, //offset范围是0~1,用于表示位置,0是指0%处的颜色
            color: "#35C3AA73"
          }, //柱图渐变色
          {
            offset: 1, //指100%处的颜色
            color: "#83E76B73"
          }
        ])
      }
    },
    {
      name: "产值",
      type: "bar",
      yAxisIndex: 1,  // 使用第二个Y轴
      barWidth: "14px", // 柱状图大小
      data: [],
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
          {
            //代表渐变色从正上方开始
            offset: 0, //offset范围是0~1,用于表示位置,0是指0%处的颜色
            color: "#35C3C373"
          }, //柱图渐变色
          {
            offset: 1, //指100%处的颜色
            color: "#408CF173"
          }
        ])
      }
    }
  ],
  xAxis: {
    type: "category",
    data: [],
    axisLine: {
      lineStyle: {
        color: "#61BCB1"
      }
    }
  },
  // 双Y轴
  yAxis: [
    {
      type: "value",
      name: "产量:KG",
      splitLine: {  // 背景辅助线
        lineStyle: {
          color: "#023735",
          type: "dashed" // 线型为虚线
        }
      },
      axisLine: {
        lineStyle: {
          color: "#61BCB1" // 设置Y轴线的颜色
        }
      }
    },
    {
      type: "value",
      name: "产值:万元",
      position: "right",
      splitLine: {
        show: false
      },
      axisLine: {
        lineStyle: {
          color: "#61BCB1" // 设置Y轴线的颜色
        }
      }
    }
  ]
}