Echarts implements switching different X-axes in one graph (example code)

Echarts implements switching different X-axes in one graph (example code)

Rendering

If you want to achieve the effect shown in the picture below, please continue reading and go directly to the animated picture!

Please add a description of the image

method

Because the project needs to display a lot of data charts, I chose to encapsulate each chart into a vue component for reference.
Here is a complete code. When quoting, please note that when getting data from the database, you need to change to your own database and define the objects you need and add them to the array you set:

<template>
  <div>
    <div id="main" style="height:350px;width:100%"></div>
  </div>
</template>
<script>
import echarts from 'echarts'
export default {
 data() {
    return {
      ans:[],
      // dayX: [], // X-axis of the day weekX: [], // X-axis of the week monthX: [], // X-axis of the month yearX: [], // X-axis of the year timeX: [], // X-axis of any time period dataY: [] // Y-axis }
  },
 created() {
    this.fetchData()
  },
  
methods: {
//Get the data in the database fetchData() {
    this.axios({
          method: 'GET',
          url: 'http://localhost:8080/xxxx/xxxx' }).then(function(resp) {
          console.log("oxygen ===>",resp.data)
          let num = resp.data.length //Get the length of the array for (let i = 0; i <num; i++) {
            //Create an object let arr = {}
            arr.timeX = resp.data[i].chkDate.slice(5, 10)
            arr.timeY = resp.data[i].oxgnSaturation
            vm.ans.push(arr)

          }

        })
     },
       init(dataX, dataY) {
      this.myChart = echarts.init(document.getElementById('main'))

      let option = {
        legend: {
          icon: 'stack',
          // data: ['that day', 'that month', 'that year'],
          data: ['this week', 'this month', 'this year', 'selected time period'],
          selectedMode: 'single', // Single selection selected: {
            This week: true,
            Current month: false,
            Current year: false,
            Selected time period: false
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer:
            type: 'cross'
          },
          //Custom display label formatter:function(params) {
            return params[0].name + '<br>Blood oxygen: '+params[0].data+' %'
          }
        },
        // Toolbar toolbox: {
          feature:
            saveAsImage: {} //You can take a screenshot of the line chart and save it.}
        },
        grid: {
          left: 10, //The distance between the component and the left side of the container right: 10,
          top: 30,
          bottom: 20,
          containLabel: true
        },

        dataZoom: [ // Use the mouse to control the zoom in and out of the line chart {
            show: true,
            type: 'inside',
            filterMode: 'none',
            xAxisIndex: [0]

          },
          {
            show: true,
            type: 'inside',
            filterMode: 'none',
            yAxisIndex: [0]

          }
        ],
        xAxis:
          type: 'category',
          miniInterval: 3,
          boundaryGap: false,
          axisTick: {
            show:false
          },
          splitLine: {
            // X-axis separator line style show: true,
            lineStyle:
              color: ['#f3f0f0'],
              width: 1,
              type: 'solid'
            }
          },
          data: dataX
        },
        yAxis: [
          {
            name: "Blood oxygen trend chart",
            type: 'value',
            splitLine: {
              // Y axis separator line style show: true,
              lineStyle:
                color: ['#f3f0f0'],
                width: 1,
                type: 'solid'
              }
            }
          }
        ],
        series: dataY

      }
      
  		this.myChart.on('legendselectchanged', obj => {
        var options = this.myChart.getOption()
        //Here is the choice of which x-axis to switch, then it will switch the Y value if (obj.name == 'this week'){
          options.xAxis[0].data = this.weekX
        }else if (obj.name == 'this month'){
          options.xAxis[0].data = this.monthX
        }else if (obj.name == 'that year'){
          options.xAxis[0].data = this.yearX
        }else if (obj.name == 'selected time period'){
          options.xAxis[0].data = this.timeX
        }

        this.myChart.setOption(options, true)
      })

      // Display the chart using the configuration items and data just specified.
      this.myChart.setOption(option)

			
  },
    mounted() {

    setTimeout(() => {
      this.$nextTick(() => {

        this.monthX = (this.res.map(item => item.monthX)).filter(Boolean) //Filter out undefined, NaN, null, empty string this.weekX = (this.res.map(item => item.weekX)).filter(Boolean) //Filter out undefined, NaN, null, empty string this.yearX = (this.res.map(item => item.yearX)).filter(Boolean) //Filter out undefined, NaN, null, empty string this.timeX = (this.ans.map(item => item.timeX)).filter(Boolean) //Filter out undefined, NaN, null, empty string //Assign values ​​to dataY. If you want one X-axis to correspond to multiple Y values, you can add a {}
        this.dataY.push({
          name: 'Current Month',
          type: 'line', // straight line
          itemStyle: {
            normal: {
              color: '#2E2E2E',
              lineStyle:
                color: '#2E2E2E',
                width: 2
              }
            }
          },
          data: this.res.map(item => item.monthY)
        })

        this.dataY.push({ //Here you can customize the display method and color of a broken line name: 'this week',
          type: 'line',
          itemStyle: {
            normal: {
              color: '#FF0000',
              lineStyle:
                color: '#FF0000',
                width: 2
              }
            }
          },
          data: this.res.map(item => item.weekY)
        })


        this.dataY.push({ //Here you can customize the display method and color of a broken line name: '年', //This must be consistent with lengen type: 'line',
          itemStyle: {
            normal: {
              color: '#0404B4',
              lineStyle:
                color: '#0404B4',
                width: 2
              }
            }
          },
          data: this.res.map(item => item.yearY)
        })

        this.dataY.push({ //Here you can customize the display method and color of a broken line name: 'Selected time period',
          type: 'line',
          itemStyle: {
            normal: {
              color: '#DF01D7',
              lineStyle:
                color: '#DF01D7',
                width: 2
              }
            }
          },
          data: this.ans.map(item => item.timeY)
        })

        this.init(this.weekX, this.dataY) //Initialized data display window.onresize = this.myChart.resize //Window size icon adaptive })
    }, 1000)
  }
}
</script>

Finished, completed

This is the end of this article about how to switch different X-axes in one graph in Echarts. For more information about how to switch different X-axes in one graph in Echarts, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Solution to Echarts chart not displaying when div is switched dynamically
  • Vue tab switching, solve the problem that the width of echartst chart is only 100px
  • echarts implements map timing switching scatter points and multi-chart cascade linkage detailed explanation
  • Solution to the problem that echarts does not display when switching the Bootstrap tab (Tab) plugin
  • Example of js data interaction method for switching four charts on the same page of echarts

<<:  CSS to achieve the sticky effect of two balls intersecting sample code

>>:  Solve the problem of secure_file_priv null

Recommend

Introduction to common commands and shortcut keys in Linux

Table of contents 1 System Introduction 2 System ...

CSS3 Tab animation example background switching dynamic effect

CSS 3 animation example - dynamic effect of Tab b...

Let's talk about the two functions of try catch in Javascript

The program is executed sequentially from top to ...

MySQL 8.0.18 Installation Configuration Optimization Tutorial

Mysql installation, configuration, and optimizati...

How to filter out duplicate data when inserting large amounts of data into MySQL

Table of contents 1. Discover the problem 2. Dele...

Vue scroll down to load more data scroll case detailed explanation

vue-infinite-scroll Install npm install vue-infin...

Detailed explanation of Vue development website SEO optimization method

Because the data binding mechanism of Vue and oth...

Detailed explanation of the use of Linux time command

1. Command Introduction time is used to count the...

Detailed explanation of how to use Teleport, a built-in component of Vue3

Table of contents 1. Teleport usage 2. Complete t...

Discussion on the numerical limit of the ol element in the html document

Generally speaking, it is unlikely that you will ...

html page!--[if IE]...![endif]--Detailed introduction to usage

Copy code The code is as follows: <!--[if IE]&...

Detailed example of concatenating multiple fields in mysql

The MySQL query result row field splicing can be ...

SQL statements in Mysql do not use indexes

MySQL query not using index aggregation As we all...