前言
笔者近期接到了一个 echarts 双 x 轴改造的需求,大致上是需要实现一个在时间轴上标注节假日的需求,为此,专门写了这么一篇文章记录自己学习了解这部分的过程,希望能对你有所帮助鸭~
实现流程
背景知识
echarts
中,影响我们配置的主要是 option
,而影响 x
轴的配置是xAxis
,一般我们配一个x
轴的时候,我们会把 xAxis
设置为一个对象,但当我们需要设置多个x
轴的时候,我们需要把xAxis
设置为一个对象,对象中的每一个值就对应一个x
轴,我们来看一个简单的双x
轴柱状图的实现过程:
实现效果:
自己动手:playground
options 配置:
ts
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
轴中,设置了position
为true
,这代表我们的第二个x
轴在顶行,如上图展示的 1-5。series 中的
xAxisIndex
:这是一个系列(series)的配置项,用于指定该系列使用哪个 X 轴。它的值是一个整数,表示 X 轴在xAxis
配置数组中的索引。
axisLabel
:这是一个轴(axis)的配置项,用于设置轴上标签的显示样式。axisLabel
是一个对象,包含一些属性,如show
、fontSize
、color
等。例如,show
属性用于控制标签是否显示,fontSize
属性用于设置标签的字体大小,color
属性用于设置标签的颜色。
动手实操
在我们了解了一些基本概念之后,我们就可以动手来做啦!
实现效果:
自己动手:playground
options配置:
ts
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
标记节假日的样式.
ts
markLine: { data: [ { xAxis: 1, label: { show: false, }, }, ], symbol: 'none', lineStyle: { type: 'dotted', // 设置节假日标线为点状线 width: 2, // 设置节假日标线宽度 color: 'red', // 设置节假日标线颜色 }, silent: true, tooltip: { trigger: 'none', }, animationDuration: 600, },
像这样~
那么这就是本篇文章的全部内容啦,我是阳🌲,感谢你的观看~