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

WeChat applet calculator example

This article shares the specific code of the WeCh...

Detailed explanation of how MySQL (InnoDB) handles deadlocks

1. What is deadlock? The official definition is a...

How to disable IE10's password clear text display and quick clear function

IE10 provides a quick clear button (X icon) and a ...

Detailed process record of nginx installation and configuration

Table of contents 1 Introduction to nginx 1 What ...

Summary of Linux commands commonly used in work

Use more open source tools such as docker and kub...

Detailed graphic tutorial on installing centos7 virtual machine in Virtualbox

1. Download centos7 Download address: https://mir...

Table Tag (table) In-depth

<br />Table is a tag that has been used by e...

Web front-end performance optimization

Web front-end optimization best practices: conten...

5 cool and practical HTML tags and attributes introduction

In fact, this is also a clickbait title, and it c...

Solve the problem of resetting the Mysql root user account password

Problem description: The following error message ...

Vue uses echart to customize labels and colors

This article example shares the specific code of ...

Native JS to implement hover drop-down menu

JS implements a hover drop-down menu. This is a s...

Discussion on Web Imitation and Plagiarism

A few months after entering the industry in 2005, ...