likes
comments
collection
share

Echarts 的双 x 轴实现思路

作者站长头像
站长
· 阅读数 11

前言

笔者近期接到了一个 echarts 双 x 轴改造的需求,大致上是需要实现一个在时间轴上标注节假日的需求,为此,专门写了这么一篇文章记录自己学习了解这部分的过程,希望能对你有所帮助鸭~

实现流程

背景知识

echarts 中,影响我们配置的主要是 option,而影响 x 轴的配置是xAxis,一般我们配一个x轴的时候,我们会把 xAxis 设置为一个对象,但当我们需要设置多个x轴的时候,我们需要把xAxis设置为一个对象,对象中的每一个值就对应一个x轴,我们来看一个简单的双x轴柱状图的实现过程:

实现效果:Echarts 的双 x 轴实现思路

自己动手:playground

options 配置:

option = {
  xAxis: [
    {
      type: 'category',
      data: ['A', 'B', 'C', 'D', 'E'],
      axisLabel: {
        show: true,
      },
    },
    {
      type: 'category',
      data: ['1', '2', '3', '4', '5'],
      axisLabel: {
        show: true,
      },
      position: 'top',
    },
  ],
  yAxis: {
    type: 'value',
  },
  series: [
    {
      name: 'Series 1',
      type: 'bar',
      data: [10, 20, 30, 40, 50],
      xAxisIndex: 0,
    },
    {
      name: 'Series 2',
      type: 'bar',
      data: [15, 25, 35, 45, 55],
      xAxisIndex: 1,
    },
  ],
};

我们在xAxis里面的第二个对象,也就是第二个x轴中,设置了positiontrue,这代表我们的第二个x轴在顶行,如上图展示的 1-5。

series 中的 xAxisIndex:这是一个系列(series)的配置项,用于指定该系列使用哪个 X 轴。它的值是一个整数,表示 X 轴在 xAxis 配置数组中的索引。

axisLabel:这是一个轴(axis)的配置项,用于设置轴上标签的显示样式。axisLabel 是一个对象,包含一些属性,如 showfontSizecolor 等。例如,show 属性用于控制标签是否显示,fontSize 属性用于设置标签的字体大小,color 属性用于设置标签的颜色。

动手实操

在我们了解了一些基本概念之后,我们就可以动手来做啦!

实现效果:Echarts 的双 x 轴实现思路

自己动手:playground

options配置:

option = {
  xAxis: [
    {
      type: 'category',
      data: ['2022-01-01', '2022-01-02', '2022-01-03', '2022-01-04', '2022-01-05'],
      axisLabel: {
        show: true,
      },
    },
    {
      type: 'category',
      data: ['', 'Holiday', '', '', ''],
      axisLabel: {
        show: true,
      },
      axisLine: {
        lineStyle: {
          type: 'dashed',
        },
      },
      axisTick: {
        show: false,
      },
      position: 'top',
    },
  ],
  yAxis: {
    type: 'value',
  },
  series: [
    {
      name: 'Series 1',
      type: 'line',
      data: [10, 20, 30, 40, 50],
      xAxisIndex: 0,
      markLine: {
        data: [
          {
            xAxis: 1,
            label: {
              show: false,
            },
          },
        ],
        symbol: 'none',
        lineStyle: {
          type: 'dashed',
          width: 1,
          color: 'rgb(231,232,233)',
        },
        silent: true,
        tooltip: {
          trigger: 'none',
        },
        animationDuration: 600,
      },
    },
  ],
};
  • 首先我们第一个x轴的参数是时间,第二个x轴的参数是holiday
  • axisLine.lineStyle.type = 'dashed' 使得第二条x轴变成虚线。
  • axisTick.show = false使得第二条x轴的凸起消失。

by the way, 如果你想要优化holiday的样式,可以使用axisLabel以及使用markLine标记节假日的样式.

markLine: { data: [ { xAxis: 1, label: { show: false, }, }, ], symbol: 'none', lineStyle: { type: 'dotted', // 设置节假日标线为点状线 width: 2, // 设置节假日标线宽度 color: 'red', // 设置节假日标线颜色 }, silent: true, tooltip: { trigger: 'none', }, animationDuration: 600, },

像这样~

那么这就是本篇文章的全部内容啦,我是阳🌲,感谢你的观看~