Apache ECharts For React – Data Zoom

Photo by Carlos Muza on Unsplash

Introduction

Data zoom is a powerful feature in data visualization that allows you to zoom in and out of specific parts of your data. Data zoom is handy when working with large datasets or focusing on specific data points. This blog post will show you how to use data zoom with Apache ECharts for React. Apache ECharts is a popular, open-source data visualization library that provides a wide range of chart types and customization options. React, on the other hand, is a highly modular and reusable JavaScript library for building user interfaces. Combining the power of Apache ECharts and React allows you to create dynamic, interactive data visualizations that allow for data zoom. In this tutorial, we will guide you through using data zoom with Apache ECharts for React and provide tips and best practices along the way.

Both example charts are modified examples from Apache ECharts.

About Apache ECharts

ECharts was originally developed by Baidu and later has been made part of the Apache Software Foundation. The parent company Apache, is the worlds largest open source foundation. ECharts is a a powerful, interactive charting and data visualization library without a steep learning curve.
Best of all, it’s free!

Source Files – Coming Soon

GitHub

Libraries

echarts-for-react and echarts. Install echarts library if you want access to shading features for this example.

npm i echarts-for-react echarts

Generate Fake Data

The data generation example below is taken from the ECharts example code.

  let base = +new Date(2016, 9, 3);
  let oneDay = 24 * 3600 * 1000;
  let valueBase = Math.random() * 300;
  let valueBase2 = Math.random() * 50;
  let data_high = [];
  let data_low = [];
  for (var i = 1; i < 10; i++) {
    var now = new Date((base += oneDay));
    var dayStr = [now.getFullYear(), now.getMonth() + 1, now.getDate()].join('-');
    valueBase = Math.round((Math.random() - 0.5) * 20 + valueBase);
    valueBase <= 0 && (valueBase = Math.random() * 300);
    data_high.push([dayStr, valueBase]);
    valueBase2 = Math.round((Math.random() - 0.5) * 20 + valueBase2);
    valueBase2 <= 0 && (valueBase2 = Math.random() * 50);
    data_low.push([dayStr, valueBase2]);
  }

The code above generate the following data. One table with high values labeled data_high and lower values data_low.

Line Chart with a Few X-Axis Data Points

Code for a simple Bar Chart.

import React from 'react';
import ReactECharts from 'echarts-for-react';
import * as echarts from 'echarts'

export default function GantZoomChart() {

  let base = +new Date(2016, 9, 3);
  let oneDay = 24 * 3600 * 1000;
  let valueBase = Math.random() * 300;
  let valueBase2 = Math.random() * 50;
  let data = [];
  let data2 = [];
  for (var i = 1; i < 10; i++) {
    var now = new Date((base += oneDay));
    var dayStr = [now.getFullYear(), now.getMonth() + 1, now.getDate()].join('-');
    valueBase = Math.round((Math.random() - 0.5) * 20 + valueBase);
    valueBase <= 0 && (valueBase = Math.random() * 300);
    data.push([dayStr, valueBase]);
    valueBase2 = Math.round((Math.random() - 0.5) * 20 + valueBase2);
    valueBase2 <= 0 && (valueBase2 = Math.random() * 50);
    data2.push([dayStr, valueBase2]);
  }

  const option = {
    title: {
      left: 'center',
      text: 'Tootip and dataZoom on Mobile Device'
    },
    legend: {
      top: 'bottom',
      data: ['Intention']
    },
    tooltip: {
      triggerOn: 'none',
      position: function (pt) {
        return [pt[0], 130];
      }
    },
    toolbox: {
      left: 'center',
      itemSize: 25,
      top: 55,
      feature: {
        dataZoom: {
          yAxisIndex: 'none'
        },
        restore: {}
      }
    },
    xAxis: {
      type: 'time',
      axisPointer: {
        value: '2016-10-7',
        snap: true,
        lineStyle: {
          color: '#7581BD',
          width: 2
        },
        label: {
          show: true,
          formatter: function (params) {
            return echarts.format.formatTime('yyyy-MM-dd', params.value);
          },
          backgroundColor: '#7581BD'
        },
        handle: {
          show: true,
          color: '#7581BD'
        }
      },
      splitLine: {
        show: false
      }
    },
    yAxis: {
      type: 'value',
      axisTick: {
        inside: true
      },
      splitLine: {
        show: false
      },
      axisLabel: {
        inside: true,
        formatter: '{value}\n'
      },
      z: 10
    },
    grid: {
      top: 110,
      left: 15,
      right: 15,
      height: 160
    },
    dataZoom: [
      {
        type: 'inside',
        throttle: 50
      }
    ],
    series: [
      {
        name: 'Fake Data',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 5,
        sampling: 'average',
        itemStyle: {
          color: '#0770FF'
        },
        stack: 'a',
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgba(58,77,233,0.8)'
            },
            {
              offset: 1,
              color: 'rgba(58,77,233,0.3)'
            }
          ])
        },
        data: data
      },
      {
        name: 'Fake Data',
        type: 'line',
        smooth: true,
        stack: 'a',
        symbol: 'circle',
        symbolSize: 5,
        sampling: 'average',
        itemStyle: {
          color: '#F2597F'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgba(213,72,120,0.8)'
            },
            {
              offset: 1,
              color: 'rgba(213,72,120,0.3)'
            }
          ])
        },
        data: data2
      }
    ]
  };

  return (

    <ReactECharts
      option={option}
      style={{ height: 400 }}
      // opts={{ locale: 'FR' }}
    />

  )
}

Toolbox

Initial setup at the top to position the toolbox button. Using left, itemSize, and top for positioning and icon button size.

Data Zoom (Toolbox only)

Under the toolBox property, enable the dataZoom feature. By setting show to true, the zoom in and out icon buttons will be available. The scroll wheel on the mouse can also enable zoom.

Restore

Under the toolBox property, enable the restore feature. By setting show to true (or leaving it blank will default to true), it will show the reset icon to restore the chart.

toolbox: {
  left: 'center',
  itemSize: 25,
  top: 55,
  feature: {
    dataZoom: {
       show: false
     },
     restore: {show: true}
  }
},

Tooltip

The tooltip is only enabled when the slider control is clicked on and dragged.

If tooltip was left blank it would show all the the time which is not ideal.

Code below for enabling the tooltip to only show when clicked or dragged.

tooltip: {
      triggerOn: 'hover',
      position: function (pt) {
        return [pt[0], 130];
      }
},

X and Y Axis

Add the data labels and adjust the font size and rotation for xAxis and yAxis properties,

Code below results in the angled xAxis labels.

 xAxis: {
      type: 'time',
      axisPointer: {
        value: '2016-10-7',
        snap: true,
        lineStyle: {
          color: '#7581BD',
          width: 2
        },
        label: {
          show: true,
          formatter: function (params) {
            return echarts.format.formatTime('yyyy-MM-dd', params.value);
          },
          backgroundColor: '#7581BD'
        },
        handle: {
          show: true,
          color: '#7581BD'
        }
      },
      splitLine: {
        show: false
      }
 },

X and Y Axis

Add the data labels and adjust the font size and rotation for xAxis and yAxis properties,

 yAxis: {
      type: 'value',
      axisTick: {
        inside: true
      },
      splitLine: {
        show: false
      },
      axisLabel: {
        inside: true,
        formatter: '{value}\n'
      },
      z: 10
    },

Grid

Line Chart

Under the series property there is name, type, and data. You can set the type to linebarpiescatterradar etc.

    grid: {
      top: 110,
      left: 15,
      right: 15,
      height: 160
    },

Example: Change from type: ‘bar’, t

Data Zoom

Line Chart

Under the series property there is name, type, and data. You can set the type to linebarpiescatterradar etc.

 dataZoom: [
      {
        type: 'inside',
        throttle: 50
      }
    ],

Series

Line Chart

Under the series property defines the type of chart and it’s rendering properties. This chart has two line charts stacked on top of eachother. Using the areaStyle property we can shade the area underneath the lines.

Without Area Shading

With Area Shading

Other properties enabled are the stack option. Having both lines on the same stack ‘a’ allow the higher line chart to be stacked on the lower line.

Without stack defined.

stack: 'a',
areaStyle: {
  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
    {
      offset: 0,
      color: 'rgba(58,77,233,0.8)'
    },
    {
      offset: 1,
      color: 'rgba(58,77,233,0.3)'
    }
  ])
},

Line chart with a High Number of Data Points

The Source code for the line chart with 20000 data points.

import React from 'react';
import ReactECharts from 'echarts-for-react';
import * as echarts from 'echarts'

export default function AreaZoomChart() {

  let base = +new Date(1968, 9, 3);
  let oneDay = 24 * 3600 * 1000;
  let date = [];
  let data = [Math.random() * 300];
  for (let i = 1; i < 20000; i++) {
    var now = new Date((base += oneDay));
    date.push([now.getFullYear(), now.getMonth() + 1, now.getDate()].join('/'));
    data.push(Math.round((Math.random() - 0.5) * 20 + data[i - 1]));
  }

  const option = {
    tooltip: {
      trigger: 'axis',
      position: function (pt) {
        return [pt[0], '10%'];
      }
    },
    title: {
      left: 'center',
      text: 'Large Area Chart'
    },
    toolbox: {
      feature: {
        dataZoom: {
          yAxisIndex: 'none'
        },
        restore: {},
        saveAsImage: {}
      }
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: date
    },
    yAxis: {
      type: 'value',
      boundaryGap: [0, '100%']
    },
    dataZoom: [
      {
        type: 'inside',
        start: 0,
        end: 10
      },
      {
        start: 0,
        end: 10
      }
    ],
    series: [
      {
        name: 'Fake Data',
        type: 'line',
        symbol: 'none',
        sampling: 'lttb',
        itemStyle: {
          color: 'rgb(255, 70, 31)'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgb(255, 158, 68)'
            },
            {
              offset: 1,
              color: 'rgb(255, 70, 31)'
            }
          ])
        },
        data: data
      }
    ]
  };

  return (

    <ReactECharts
      option={option}
      style={{ height: 400 }}
      // opts={{ locale: 'FR' }}
    />

  )
}

Data Zoom

This type of data zoom put a control at the bottom of the chart.

dataZoom: [
      {
        type: 'inside',
        start: 0,
        end: 10
      },
      {
        start: 0,
        end: 10
      }
],

Render Chart Component

Note: The MUI IconButton has a property of tabIndex and you which should be set to “-1“, otherwise when the user hits the tab button it will go to the icon button instead of the next field.

 <ReactECharts
    option={option}
   style={{ height: 400 }}
 />

Conclusion

In conclusion, data zoom is a valuable feature in data visualization that can help you focus on specific parts of your data. Using data zoom with Apache ECharts for React, you can create dynamic, interactive visualizations that allow your audience to focus on the most relevant data. Throughout this blog post, we walked through the process of using data zoom with Apache ECharts for React and provided tips and best practices to help you along the way. Whether you are a seasoned developer or just starting, this tutorial provides a great introduction to using data zoom with Apache ECharts for React. It will help you create more effective data visualizations for your next project.

Check out some of the other examples under the ECharts section below.

https://fullstacksoup.blog/category/echarts/