How to add Google Charts to your web page?


We will include a Google Chart to the web page using the google.charts.load(). The draw() method is used to draw the chart. To display, use the BarChart class. First, the chart data is configured. The data of the chart is in a table.

Configure the Chart Data

Let us first create a function of the chart data. Configure the data to be displayed on the chart. DataTable is a special table structured collection which contains the data of the chart.

function drawChart() {
   var data = google.visualization.arrayToDataTable([
      ["Year", "India"],
      ["2019", 500],
      ["2020", 800],
      ["2021", 1000],
      ["2022", 1200],
      ["2023", 1400]
   ]);

Set the Chart Title

Here, options of the chart are configured −

var options = { title: "Educated people(in millions)" };

Draw the Chart Using the BarChart Class

We've used BarChart class to show area based chart. The data represents the json data and options represents the configuration which Google Chart library uses to draw a chart −

var chart = new google.visualization.BarChart(
   document.querySelector(".barchartContainer")
);
chart.draw(data, options);

Place the Chart

The chart is placed inside the div. The container is styled like this with the width, heigh and margin properties −

.barchartContainer {
   width: 550px;
   height: 400px;
   margin: 0 auto;
   font-weight: bold;
}

Example

To add Google Charts to your web page, the code is as follows −

<!DOCTYPE html>
<html>
<head>
   <title>Google Charts Tutorial</title>
   <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
   <script type="text/javascript">
      google.charts.load("current", { packages: ["corechart"] });
   </script>
   <style>
      .barchartContainer {
         width: 550px;
         height: 400px;
         margin: 0 auto;
         font-weight: bold;
      }
      body {
         font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
      }
   </style>
</head>
<body>
   <h1 style="text-align: center;">
   Adding google charts to your web page Example
   </h1>
   <div class="barchartContainer"></div>
   <script language="JavaScript">
      function drawChart() {
         var data = google.visualization.arrayToDataTable([
         ["Year", "India"],
         ["2019", 500],
         ["2020", 800],
         ["2021", 1000],
         ["2022", 1200],
         ["2023", 1400]
         ]);
         var options = { title: "Educated people(in millions)" };
         var chart = new google.visualization.BarChart(
            document.querySelector(".barchartContainer")
         );
         chart.draw(data, options);
      }
      google.charts.setOnLoadCallback(drawChart);
   </script>
</body>
</html>

Updated on: 15-Nov-2023

261 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements