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

Deployment and Chinese translation of the docker visualization tool Portainer

#docker search #docker pull portainer 1. Download...

Detailed explanation of the principle of Docker image layering

Base image The base image has two meanings: Does ...

Methods and steps for deploying go projects based on Docker images

Dependence on knowledge Go cross-compilation basi...

Detailed explanation of how Tomcat implements asynchronous Servlet

Preface Through my previous Tomcat series of arti...

Detailed explanation of virtual DOM and diff algorithm in react

The role of virtual DOM First of all, we need to ...

Tutorial on building svn server with docker

SVN is the abbreviation of subversion, an open so...

Methods and steps to access Baidu Maps API with JavaScript

Table of contents 1. Baidu Map API Access 2. Usin...

JavaScript data transmission between different pages (URL parameter acquisition)

On web pages, we often encounter this situation: ...

How to solve the Mysql transaction operation failure

How to solve the Mysql transaction operation fail...

Detailed explanation of the use of base tag in HTML

In requireJS, there is a property called baseURL....

Calling the search engine in the page takes Baidu as an example

Today, it suddenly occurred to me that it would be...

Brief introduction and usage of Table and div

Web front end 1 Student ID Name gender age 01 Zha...

JavaScript to implement a simple web calculator

background Since I was assigned to a new project ...

The difference between ${param} and #{param} in MySQL

The parameter passed by ${param} will be treated ...