React Google Chart: A Complete Guide to Interactive Data Visualizations

React Google Chart is a powerful and easy-to-use tool for creating interactive and responsive data visualizations in web applications. It enables developers to present dynamic data effectively, making it a popular choice for building data-rich React applications. In this blog, we’ll guide you through setting up Google Charts in React and explore various chart types available in its library.

Why Google Charts?

Google Charts offers several benefits, such as:

  • Ease of Use: Minimal configuration is needed to generate high-quality charts.
  • Interactivity: Charts are interactive, allowing users to hover over data points, zoom, and more.
  • Customizability: Each chart can be extensively customized.
  • Cross-browser Compatibility: Works seamlessly across different browsers.

You can easily unlock these benefits when integrating React Google Chart into your applications.

Getting Started with Google Charts in React

Step 1: Install Google Charts Library

To start using React Google Chart, install the react-google-charts package, which provides React components for the Google Charts library.

npm install react-google-charts

Related read: Unlock the Power of npm: Turn Your React Components into a Library

Step 2: Import and Use Basic Google Charts

After installing the package, you can easily integrate charts by importing the necessary components.

import React from "react";
import { Chart } from "react-google-charts";


function App() {
  const data = [
    ["Year", "Sales", "Expenses"],
    ["2017", 1000, 400],
    ["2018", 1170, 460],
    ["2019", 660, 1120],
    ["2020", 1030, 540],
  ];


  const options = {
    title: "Company Performance",
    curveType: "function",
    legend: { position: "bottom" },
  };


  return (
    <div>
      <h1>Google Charts in React</h1>
      <Chart
        chartType="LineChart"
        data={data}
        options={options}
        width="100%"
        height="400px"
      />
    </div>
  );
}

export default App;

Basic Line Chart Example

The code above generates a simple Line Chart. It takes data and options as props. The data is an array where the first element is the header (for columns), and the subsequent elements represent the data rows.

Advanced Customizations with React Google Chart

Google Charts provides several options to customize the appearance and behavior of your charts. Let’s explore these options with some examples of advanced charts.

➡️ Bar Chart with Custom Colors and Tooltips

import React from "react";
import { Chart } from "react-google-charts";


function CustomBarChart() {
  const data = [
    ["City", "2010 Population", "2000 Population"],
    ["New York City, NY", 8175000, 8008000],
    ["Los Angeles, CA", 3792000, 3694000],
    ["Chicago, IL", 2695000, 2896000],
    ["Houston, TX", 2099000, 1953000],
    ["Philadelphia, PA", 1526000, 1517000],
  ];


  const options = {
    title: "Population of Largest U.S. Cities",
    chartArea: { width: "50%" },
    colors: ["#b0120a", "#ffab91"],
    hAxis: {
      title: "Total Population",
      minValue: 0,
    },
    vAxis: {
      title: "City",
    },
    tooltip: {
      isHtml: true,
      textStyle: {
        color: "#000",
        fontSize: 14,
      },
    },
 };


 return (
   <div>
     <h2>Bar Chart with Custom Colors and Tooltips</h2>
     <Chart
        chartType="BarChart"
        data={data}
        options={options}
        width="100%"
        height="400px"
     />
   </div>
  );
}

export default CustomBarChart;

In this bar chart:

  • The colors option lets us assign custom colors to each data series.
  • The tooltip option allows custom HTML formatting for tooltips.
  • ChartArea ensures the chart is well-spaced and the axis titles don’t overlap with chart elements.

➡️ Pie Chart with Custom Slices and 3D Effect

import React from "react";
import { Chart } from "react-google-charts";


function CustomPieChart() {
  const data = [
    ["Task", "Hours per Day"],
    ["Work", 11],
    ["Eat", 2],
    ["Commute", 2],
    ["Watch TV", 2],
    ["Sleep", 7],
  ];


  const options = {
    title: "My Daily Activities",
    is3D: true,
    slices: {
      1: { offset: 0.2 }, // "Eat" slice
      3: { offset: 0.1 }, // "Watch TV" slice
    },
  };


  return (
    <div>
      <h2>Pie Chart with 3D Effect</h2>
      <Chart
        chartType="PieChart"
        data={data}
        options={options}
        width="100%"
        height="400px"
      />
    </div>
  );
}

export default CustomPieChart;

Here:

  • The is3D: true option adds a 3D effect to the Pie Chart.
  • The slices object allows for customization of individual pie slices, like adding an offset to highlight a specific section.

➡️ Geo Chart with Region Customization

import React from "react";
import { Chart } from "react-google-charts";


function GeoChartExample() {
  const data = [
    ["Country", "Popularity"],
    ["Germany", 200],
    ["United States", 300],
    ["Brazil", 400],
    ["Canada", 500],
    ["France", 600],
    ["RU", 700],
  ];


  const options = {
    colorAxis: { colors: ["#e7711c", "#4374e0"] }, // Orange to blue gradient
    backgroundColor: "#81d4fa", // Light blue background
    datalessRegionColor: "#f8bbd0", // Pink for regions with no data
    defaultColor: "#f5f5f5", // Default grey color for other regions
  };


  return (
    <div>
      <h2>Geo Chart with Region Customization</h2>
      <Chart
        chartType="GeoChart"
        data={data}
        options={options}
        width="100%"
        height="400px"
      />
    </div>
  );
}

export default GeoChartExample;

In this Geo Chart:

  • The colorAxis option controls the gradient for data values.
  • We use datalessRegionColor and backgroundColor to customize the colors of regions without data and the chart’s background.

➡️ Combo Chart (Bar and Line Combined)

import React from "react";
import { Chart } from "react-google-charts";


function ComboChart() {
  const data = [
    ["Month", "Bolivia", "Ecuador", "Average"],
    ["2020/01", 165, 938, 614.6],
    ["2020/02", 135, 1120, 682],
    ["2020/03", 157, 1167, 623],
    ["2020/04", 139, 1110, 609.4],
    ["2020/05", 136, 691, 569.6],
  ];


  const options = {
    title: "Monthly Coffee Production by Country",
    vAxis: { title: "Cups" },
    hAxis: { title: "Month" },
    seriesType: "bars",
    series: { 2: { type: "line" } },
    colors: ["#1c91c0", "#e7711b", "#f1ca3a"],
  };


  return (
    <div>
      <h2>Combo Chart (Bar and Line)</h2>
      <Chart
        chartType="ComboChart"
        data={data}
        options={options}
        width="100%"
        height="400px"
      />
    </div>
  );
}

export default ComboChart;

In this chart:

  • We combine bar and line chart types using seriesType: “bars” and series: { 2: { type: “line” } }.
  • The third series (Average) represents a line, while the first two are bars.

Transform Your Data Into Stunning Visualizations With React Google Chart

Advanced Customizations in Google Charts

➡️ Inverting Axes

Inverting axes can be useful when switching between horizontal and vertical axes. You can do this with both bar charts and line charts by changing the hAxis and vAxis properties.

Example: Horizontal to Vertical Inversion in Bar Chart.

import React from "react";
import { Chart } from "react-google-charts";


function InvertedBarChart() {
  const data = [
    ["City", "2010 Population", "2000 Population"],
    ["New York City, NY", 8175000, 8008000],
    ["Los Angeles, CA", 3792000, 3694000],
    ["Chicago, IL", 2695000, 2896000],
    ["Houston, TX", 2099000, 1953000],
    ["Philadelphia, PA", 1526000, 1517000],
  ];


  const options = {
    title: "Population of Largest U.S. Cities",
    chartArea: { width: "50%" },
    colors: ["#b0120a", "#ffab91"],
    hAxis: {
      title: "Total Population",
      minValue: 0,
  }, 
  vAxis: {
    title: "City",
  },
  isStacked: true, // Stack bars to show cumulative population
  orientation: 'horizontal', // Invert the bars to make them horizontal
};


return (
  <div>
    <h2>Inverted Bar Chart</h2>
     <Chart
        chartType="BarChart"
        data={data}
        options={options}
        width="100%"
        height="400px"
     />
   </div>
 );
}

export default InvertedBarChart;

Explanation:

  • orientation: ‘horizontal’: This option inverts the chart, turning a standard vertical bar chart into a horizontal one.
  • isStacked: true: This stacks the bars in the chart, which can be useful for comparison.

➡️ Customizing Axes Ranges and Format

You can fine-tune the axes ranges and formats to fit specific data requirements, such as displaying currency, percentages, or date formats.

Example: Custom Axis Formats in Line Chart.

import React from "react";
import { Chart } from "react-google-charts";


function LineChartWithCustomAxes() {
  const data = [
    ["Year", "Sales", "Expenses"],
    ["2017", 1000, 400],
    ["2018", 1170, 460],
    ["2019", 660, 1120],
    ["2020", 1030, 540],
  ];


  const options = {
    title: "Company Performance",
    curveType: "function",
    legend: { position: "bottom" },
    hAxis: {
      title: "Year",
      format: "####", // Custom format for year
   },
   vAxis: {
     title: "Amount (in $)",
     minValue: 0,
     maxValue: 2000,
     format: "currency", // Format values as currency
   },
   colors: ["#1c91c0", "#e7711b"],
};


return (
  <div>
    <h2>Line Chart with Custom Axes</h2>
    <Chart
      chartType="LineChart"
      data={data}
      options={options}
      width="100%"
      height="400px"
    />
  </div>
 );
}

export default LineChartWithCustomAxes;

Explanation:

  • hAxis.format: “####”: Customizes the format of the x-axis to display the year as a four-digit number.
  • vAxis.format: “currency”: Formats the y-axis values as currency, so they are automatically prefixed with a dollar sign.

➡️ Customizing Tooltips with HTML

Google Charts allows you to fully customize tooltips by using custom HTML. You can control what gets displayed and how it’s styled.

Example: Line Chart with Custom HTML Tooltips.

import React from "react";
import { Chart } from "react-google-charts";


function CustomTooltipChart() {
  const data = [
    ["Year", "Sales", { role: "tooltip", p: { html: true } }],
    ["2017", 1000, "<div style='padding:10px'><b>Sales:</b> $1000</div>"],
    ["2018", 1170, "<div style='padding:10px'><b>Sales:</b> $1170</div>"],
    ["2019", 660, "<div style='padding:10px'><b>Sales:</b> $660</div>"],
    ["2020", 1030, "<div style='padding:10px'><b>Sales:</b> $1030</div>"],
  ];


  const options = {
    title: "Company Sales with Custom Tooltips",
    curveType: "function",
    tooltip: { isHtml: true }, // Enable HTML tooltips
    legend: { position: "bottom" },
  };


  return (
    <div>
      <h2>Line Chart with Custom HTML Tooltips</h2>
      <Chart
        chartType="LineChart"
        data={data}
        options={options}
        width="100%"
        height="400px"
      />
   </div>
  );
}

export default CustomTooltipChart;

Explanation:

  • HTML Tooltips: The tooltip object allows us to use custom HTML for each tooltip. In this example, tooltips are styled with div elements, and the role: “tooltip” key in the data array specifies that custom tooltips should be used.

➡️ Dual Y-Axis Customization (Combo Charts)

You may want to display data that requires two different Y-axes (such as sales and percentage growth). Google Charts’ ComboChart type allows for this customization.

Example: Combo Chart with Dual Y-Axis.

import React from "react";
import { Chart } from "react-google-charts";


function DualAxisComboChart() {
  const data = [
    ["Year", "Sales", "Expenses", "Profit %"],
    ["2017", 1000, 400, 25],
    ["2018", 1170, 460, 35],
    ["2019", 660, 1120, 15],
    ["2020", 1030, 540, 30],
  ];


  const options = {
    title: "Company Sales, Expenses, and Profit %",
    seriesType: "bars",
    series: {
      2: { type: "line", targetAxisIndex: 1 }, // Profit on second Y-axis
    },
    vAxes: {
      0: { title: "Sales/Expenses (in $)" },
      1: { title: "Profit %" }, // Secondary Y-axis for profit
    },
    colors: ["#1b9e77", "#d95f02", "#7570b3"],
  };


  return (
    <div>
      <h2>Combo Chart with Dual Y-Axis</h2>
      <Chart
        chartType="ComboChart"
        data={data}
        options={options}
        width="100%"
        height="400px"
      />
   </div>
  );
}

export default DualAxisComboChart;

Explanation:

  • targetAxisIndex: 1: This places the third series (profit percentage) on the secondary Y-axis.
  • vAxes: This option defines both Y-axes, with labels for each. You can use as many axes as necessary to plot different data scales on a single chart.

➡️ Dynamic Chart with Real-Time Data Updates

You can easily integrate dynamic data that updates your charts in real-time. Using state hooks in React, charts can be rendered based on changing data.

Example: Real-Time Line Chart.

import React, { useEffect, useState } from "react";
import { Chart } from "react-google-charts";


function RealTimeChart() {
  const [data, setData] = useState([
    ["Time", "Stock Price"],
    ["0", 0],
  ]);


  useEffect(() => {
    let count = 1;
    const interval = setInterval(() => {
      setData((prevData) => [
        ...prevData,
        [count.toString(), Math.floor(Math.random() * 1000)],
      ]);
      count++;
   }, 1000);


   return () => clearInterval(interval);
}, []);


const options = {
   title: "Real-Time Stock Price",
   curveType: "function",
   hAxis: { title: "Time (Seconds)" },
   vAxis: { title: "Stock Price (USD)" },
   legend: { position: "none" },
};


return (
  <div>
    <h2>Real-Time Line Chart</h2>
    <Chart
      chartType="LineChart"
      data={data}
      options={options}
      width="100%"
      height="400px"
    />
  </div>
 );
}

export default RealTimeChart;

Explanation:

  • useEffect and setInterval: The useEffect hook is used to dynamically update the
coma

Conclusion

Google Charts offers a powerful way to create interactive and customizable charts in your React application. With react-google-charts, the integration is seamless, and the variety of chart types and customizations allow you to meet any data visualization needs. By combining different chart types, and customizing colors, tooltips, axes, and more, you can create a dynamic and user-friendly interface for presenting data.

Keep Reading

Keep Reading

  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?