echarts 实战 : 想让图例颜色和元素颜色对应,怎么办?

首先,在 series 里设置颜色。

(我是用js生成 echarts 需要的option对象,所以可能很难看懂)

        normalData.sData.forEach((item, index) => {
          const object = {...baseSeriesObject}
          object.data = item.data
  
          this.setLegend(object, option, item.name, showLegendFlag)
          this.setStock(object, showStackFlag)
          this.setLegendColor(object, settingData.color[index])
  
          // 单位
          if (typeof settingData.unitFlag === "object" && settingData.unitFlag.length > 0 && settingData.xyType === "x" && settingData.unitFlag[settingData.unitFlag.length-1] !== "") {
            option.yAxis[index].axisLabel.formatter = this.getAxisLabel(settingData.unitFlag[index])
          }

          if (settingData.barWidth) {
            object.barWidth = settingData.barWidth
          }

          option.series.push(object)
        });

标红色的就是设置颜色的方法。

  setLegendColor = (object, color) => {
    if (!color || !object) {
      return object
    }
    object.normal = {
      color: color
    }
    return object
  }

最后是 legend.textStyle.color 。关键是 color 要写成函数。

    const baseLegend = {
      data:[],
      top:10,
      right:23,
      itemWidth:8,
      itemHeight:8,
      icon:'circle',
      textStyle:{
        padding:[3,5,0,3],
        fontSize:16,
        color: (params) => (params)
      },
    }
        if (typeof settingData.legendFlag === "object") {
          option.legend = Object.assign(baseLegend, settingData.legendFlag)
        } else {
          option.legend = baseLegend
        }

蓝色的箭头函数就是设置颜色的函数。没错,这么写就够了。

 

以上。

posted on 2019-11-17 09:12  fox_charon  阅读(4670)  评论(0编辑  收藏  举报

导航