Apache ECharts For React – Bar to Pie Chart Transition Animation

Photo by Carlos Muza on Unsplash

Introduction

Bar charts and pie charts are two of the most commonly used chart types for data visualization. While bar charts are great for displaying data in a compact form, pie charts provide a clear representation of data proportion. In some cases, it may be beneficial to transition from a bar chart to a pie chart to better illustrate the data. This blog post will guide you through building a bar-to-pie chart transition animation using React and Apache ECharts. By following this tutorial, you will learn how to create an engaging, interactive, and informative data visualization that can help your audience better understand your data.

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!

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

Source Code – Coming Soon

GitHub

Fake Data

Hard coded data below. Fictitious number of page hits or points for different guitarist.

const dataset = {
dimensions: ['name', 'score'],
source: [
    ['Orianthi Panagaris', 314],
    ['Eddie Van Halen', 351],
    ['Lita Ford ', 287],
    ['Don Felder', 219],
    ['Jerry Cantrell', 253],
    ['Nancy Wilson', 165],
    ['David Gilmore', 318],
    ['Alex Lifeson', 366]
  ]
};

Pie to Bar Chart

Using the universalTransition and animationDurationUpdate properties to enable the transition/morphing feature and the duration.

Pie Chart Option

Using the hard coded dataset, create a simple pie chart.

Use universalTransition to enable the transition

Use animationDurationUpdate to set the duration of the transition animation.

 const pieOption = {
  dataset: [dataset],
  series: [
    {
      type: 'pie',
      // associate the series to be animated by id
      id: 'Score',
      radius: [0, '50%'],
      universalTransition: true,
      animationDurationUpdate: 1000
    }
  ]

Bar Chart Option

Using the hard coded dataset to create a verticle bar chart.

Also uses universalTransition and animationDurationUpdate properties for the animation and duration.

const barOption = {
  dataset: [dataset],
  xAxis: {
    type: 'category',
    axisLabel: {      
      rotate: 0,
      textStyle: {
        baseline: "top",
        color: "#333",
        fontSize: 10,
        fontWeight: "bold"
      }
    },
  },
  yAxis: {},
  series: [
    {
      type: 'bar',
      // associate the series to be animated by id
      id: 'Score',
      // Each data will have a different color
      colorBy: 'data',
      encode: { x: 'name', y: 'score' },
      universalTransition: true,
      animationDurationUpdate: 1000
    }
  ]
};

X Axis

Set properties in xAxis to update the label font. Also, the rotate option is useful when labels are on the yAxis and there is not enough space.

 xAxis: {
    type: 'category',
    axisLabel: {      
      rotate: 0,
      textStyle: {
        baseline: "top",
        color: "#333",
        fontSize: 10,
        fontWeight: "bold"
      }
    },
  },

Animate with Intervals

Using setInterval() to 2000ms = 2 seconds. This will be be disable with a comment in the source files.

 const [currentChart, setCurrentChart] = React.useState(pieOption)

 React.useEffect(() => {

    let currentOption = pieOption;  

    setInterval(function () {
      currentOption = currentOption === pieOption ? barOption : pieOption;
      setCurrentChart(currentOption);
      
    }, 2000);

    setTimeout(() => {
      setIsLoaded(true)      
    }, 400);
}, []);

Toggle Charts with a Button

The legend property has the following options for the position: vertical, top, and bottom

...
  const [currentChart, setCurrentChart] = React.useState(pieOption)
   
  const toggleCharts = () => {
    
    setCurrentChart(currentChart === pieOption ? barOption : pieOption)    
    setIsMapShowing(currentChart === pieOption ? false : true)      
    
 }
...
  return (
    <>
    <button onClick={() => toggleCharts()} style={{width: '100px'}}>Toggle</button>

Render the Chart

Render the chart when isLoaded is set to true.

return (
    <>
    <button onClick={() => toggleCharts()} style={{width: '100px'}}>Toggle</button>
    <ReactEcharts option={currentChart} style={{ width: "600px", height: "400px" }} />
    </>
  );

All Together

Pie to Bar Chart Component

All the code for “./components/PieToBarChart.js”

import React from "react";
import ReactEcharts from "echarts-for-react";

const dataset = {
  dimensions: ['name', 'score'],
  source: [
    ['Orianthi Panagaris', 314],
    ['Eddie Van Halen', 351],
    ['Lita Ford ', 287],
    ['Don Felder', 219],
    ['Jerry Cantrell', 253],
    ['Nancy Wilson', 165],
    ['David Gilmore', 318],
    ['Alex Lifeson', 366]
  ]
};
const pieOption = {
  dataset: [dataset],
  series: [
    {
      type: 'pie',
      // associate the series to be animated by id
      id: 'Score',
      radius: [0, '50%'],
      universalTransition: true,
      animationDurationUpdate: 1000
    }
  ]
};
const barOption = {
  dataset: [dataset],
  xAxis: {
    type: 'category',
    axisLabel: {      
      rotate: 20,
      textStyle: {
        baseline: "top",
        color: "#333",
        fontSize: 10,
        fontWeight: "bold"
      }
    },
  },
  yAxis: {},
  series: [
    {
      type: 'bar',
      // associate the series to be animated by id
      id: 'Score',
      // Each data will have a different color
      colorBy: 'data',
      encode: { x: 'name', y: 'score' },
      universalTransition: true,
      animationDurationUpdate: 1000
    }
  ]
};

export default function PieToBarChart() {
   
  const [currentChart, setCurrentChart] = React.useState(pieOption)
   
  const toggleCharts = () => {    
    setCurrentChart(currentChart === pieOption ? barOption : pieOption)            
  }

  // React.useEffect(() => {
  //   let currentOption = pieOption;  
  //   setInterval(function () {
  //     currentOption = currentOption === pieOption ? barOption : pieOption;
  //     setCurrentChart(currentOption);      
  //   }, 2000);    
  // }, []);

  return (
    <>
      <button onClick={() => toggleCharts()} style={{width: '100px'}}>Toggle</button>      
      <ReactEcharts option={currentChart} style={{ width: "600px", height: "400px" }} />
      
    </>
  );
};

App.js – Root Component

import React from "react";
import PieToBarChart from "./components/PieToBarChart";

import './App.css'

export default function App() {

  return (
    <div className="container">
      <PieToBarChart/> 

    </div>     
  );  
}

App.css

.App {
  text-align: center;
}

.App-logo {
  height: 40vmin;
  pointer-events: none;
}

.container {
  width: 80%;
  margin: 0 auto;
  margin-top: 45px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;
}

Conclusion

In conclusion, building a bar-to-pie chart transition animation is a great way to add interactivity and engagement to your data visualization projects. The combination of React and Apache ECharts makes it possible to create dynamic, visually appealing animations to help your audience better understand your data. Throughout this blog post, we walked through the process of building a bar-to-pie chart transition animation and discussed various best practices and tips to help you along the way. Whether you are a seasoned developer or just starting, this tutorial provides a great introduction to using animation in data visualization. It will help you create dynamic and engaging visualizations for your next project.

Example of map to bar chart animation here.