echarts盒须图颜色填充

78 阅读1分钟

最近接到一个需求,需要使用 echarts 的 boxplots ,用不同颜色表现出来。不过在实现过程中遇到内部没填充颜色的问题,特此记录一下。

this.BoxplotOption = {
        tooltip: {
          trigger: 'item',
          axisPointer: { type: 'shadow' },
        },
        grid: [{ left: 50, right: 40, top: 30, bottom: 30 }],
        xAxis: [
          {
            type: 'category',
            data: boxplotNames,
            boundaryGap: true,
            name: '测点',
            splitArea: { show: false },
            axisLabel: { rotate: 30 },
          },
        ],
        yAxis: [
          {
            type: 'value',
            name: '值',
            splitArea: { show: true },
          },
        ],
        series: [
          {
            name: '箱线图',
            type: 'boxplot',
            data: echartsBoxplot.boxData,
            itemStyle: {
              // borderColor: '#3cc4ef',
              borderWidth: 2,
            },
            colorBy: 'data',
            color: boxplotColors, // 颜色数组
            tooltip: {
              formatter: function (param) {
                return [
                  param.name + ': ',
                  '最大值: ' + param.data[5],
                  '中位数: ' + param.data[3],
                  '最小值: ' + param.data[1],
                ].join('<br/>')
              },
            },
          },
          {
            name: '异常值',
            type: 'scatter',
            data: echartsBoxplot.outliers,
          },
        ],
      }

image.png

只有线段有颜色,里面没填充颜色。后面查资料才知道,colorBybarpiescatter 等图表起作用。boxplot 不自动从 colorcolorBy 映射填充色,需要显式设置 itemStyle.color。 后面改成这样就可以每个都填充各自的颜色。

series: [
  {
    name: '箱线图',
    type: 'boxplot',
    data: echartsBoxplot.boxData.map((d, i) => ({
      value: d,
      itemStyle: {
        color: boxplotColors[i] || '#73C0DE',
        borderColor: '#3cc4ef',
        borderWidth: 2
      }
    })),
    tooltip: {
      formatter: function (param) {
        return [
          param.name + ': ',
          '最大值: ' + param.data.value[5],
          '中位数: ' + param.data.value[3],
          '最小值: ' + param.data.value[1],
        ].join('<br/>')
      },
    },
  },
  {
    name: '异常值',
    type: 'scatter',
    data: echartsBoxplot.outliers,
  },
]

image.png