Your Page Title
🔍

    JS Google Chart

    Google Charts is a powerful and free JavaScript library that allows you to create a wide variety of interactive charts for your web pages. It’s known for its robust features, good documentation, and seamless integration with Google services. Unlike Chart.js or Plotly.js which are standalone libraries, Google Charts relies on loading data and chart types from Google’s servers, which might be a consideration for offline applications.

    1. Getting Started with Google Charts

    To use Google Charts, you need to load the library from Google’s servers. This is typically done in the <head> section of your HTML.

    HTML

    <!DOCTYPE html>
    <html>
    <head>
        <title>Google Charts Tutorial</title>
        <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
        <style>
            body { font-family: Arial, sans-serif; display: flex; justify-content: center; align-items: center; min-height: 100vh; background-color: #f4f4f4; }
            #chart_div {
                width: 700px;
                height: 450px;
                background-color: #fff;
                padding: 20px;
                border-radius: 8px;
                box-shadow: 0 4px 8px rgba(0,0,0,0.1);
            }
        </style>
    </head>
    <body>
        <div id="chart_div"></div>
    
        <script type="text/javascript">
            // Your JavaScript code for Google Charts will go here
        </script>
    </body>
    </html>
    

    You’ll need a div element with an id where the chart will be drawn.

    2. The Core Concepts: Loader, DataTable, and Chart Types

    Google Charts works with a specific flow:

    1. Loader: You first load the Google Charts library itself using google.charts.load(). This is followed by google.charts.setOnLoadCallback() to ensure your chart drawing function runs only after the library is fully loaded.
    2. DataTable: Data for the charts is typically organized in a google.visualization.DataTable object. This object defines the columns (with their type and label) and rows of data.
    3. Chart Type: You instantiate a specific chart object (e.g., google.visualization.ColumnChart, google.visualization.PieChart).
    4. Options: An object containing configuration options for the chart, such as title, axis labels, colors, and interactivity.
    5. Drawing: Finally, you call the draw() method on the chart object, passing the DataTable and options.

    3. Your First Chart: A Simple Column Chart

    Let’s create a basic column chart showing some fictional sales data.

    JavaScript

    // 1. Load the Visualization API and the corechart package.
    google.charts.load('current', {'packages':['corechart']});
    
    // 2. Set a callback to run when the Google Visualization API is loaded.
    google.charts.setOnLoadCallback(drawChart);
    
    // 3. Callback function that creates and draws the chart.
    function drawChart() {
        // Create the data table.
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Category'); // Column 1: Category Name (string)
        data.addColumn('number', 'Sales');    // Column 2: Sales Value (number)
    
        data.addRows([
            ['Electronics', 80000],
            ['Apparel', 60000],
            ['Home Goods', 45000],
            ['Books', 30000],
            ['Food', 70000]
        ]);
    
        // Set chart options.
        var options = {
            title: 'Company Sales Performance',
            hAxis: {
                title: 'Product Category',
                titleTextStyle: { color: '#333' }
            },
            vAxis: {
                title: 'Total Sales ($)',
                minValue: 0
            },
            colors: ['#4CAF50'], // Green bars
            legend: 'none' // No legend for a single series
        };
    
        // Instantiate and draw our chart, passing in the data and options.
        var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
        chart.draw(data, options);
    }
    

    When you open this HTML file, you’ll see a clean, interactive column chart. You can hover over bars to see tooltips and use the built-in zoom and pan functionality (if enabled).

    4. Exploring Other Chart Types

    Google Charts supports a vast array of chart types by changing the package loaded and the chart constructor.

    a. Pie Chart

    To use a Pie Chart, you still load corechart, but instantiate google.visualization.PieChart.

    JavaScript

    // Ensure corechart is loaded
    google.charts.load('current', {'packages':['corechart']});
    google.charts.setOnLoadCallback(drawPieChart);
    
    function drawPieChart() {
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Task');
        data.addColumn('number', 'Hours per Day');
        data.addRows([
            ['Work', 8],
            ['Eat', 2],
            ['Commute', 1],
            ['Watch TV', 3],
            ['Sleep', 8]
        ]);
    
        var options = {
            title: 'My Daily Activities',
            is3D: true, // Make it a 3D pie chart
            colors: ['#3366CC', '#DC3912', '#FF9900', '#109618', '#990099'] // Custom colors
        };
    
        var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
        chart.draw(data, options);
    }
    // To test, comment out the Column Chart drawChart() call and uncomment drawPieChart()
    // google.charts.setOnLoadCallback(drawPieChart);
    

    b. Line Chart

    Similar to Pie and Column, you use google.visualization.LineChart.

    JavaScript

    // Ensure corechart is loaded
    google.charts.load('current', {'packages':['corechart']});
    google.charts.setOnLoadCallback(drawLineChart);
    
    function drawLineChart() {
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Month');
        data.addColumn('number', 'Revenue');
        data.addColumn('number', 'Expenses');
        data.addRows([
            ['Jan', 1000, 400],
            ['Feb', 1170, 460],
            ['Mar', 660, 1120],
            ['Apr', 1030, 540]
        ]);
    
        var options = {
            title: 'Company Performance',
            curveType: 'function', // Makes lines smooth
            legend: { position: 'bottom' }
        };
    
        var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
        chart.draw(data, options);
    }
    // To test, uncomment the Line Chart drawLineChart() call
    // google.charts.setOnLoadCallback(drawLineChart);
    

    5. Google Charts Packages

    Not all chart types are in the corechart package. For example, to use a GeoChart (a map chart), you would load the geochart package:

    JavaScript

    // Load the geochart package
    google.charts.load('current', {'packages':['geochart']});
    google.charts.setOnLoadCallback(drawRegionsMap);
    
    function drawRegionsMap() {
        var data = google.visualization.arrayToDataTable([
            ['Country', 'Popularity'],
            ['Germany', 200],
            ['United States', 300],
            ['Brazil', 400],
            ['Canada', 500],
            ['France', 600],
            ['RU', 700] // Russia
        ]);
    
        var options = {
            title: 'Website Visitors by Country',
            colorAxis: {colors: ['#e31b23', '#00853f']}, // Red to Green gradient
            backgroundColor: '#81d4fa', // Light blue background
            datalessRegionColor: '#f8f8f8' // Color for countries with no data
        };
    
        var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
        chart.draw(data, options);
    }
    // google.charts.setOnLoadCallback(drawRegionsMap); // Uncomment to test GeoChart
    

    You can load multiple packages by listing them in the packages array: {'packages':['corechart', 'geochart']}.

    6. Dynamic Updates and Events

    Google Charts can be updated dynamically by simply calling chart.draw(data, options) again with new data or options. They also expose events that you can listen to, such as select (when a user selects a part of the chart) or ready (when the chart has finished drawing).

    JavaScript

    // Inside your drawChart function for the Column Chart:
    // ... (before chart.draw)
    google.visualization.events.addListener(chart, 'select', function() {
        var selection = chart.getSelection();
        if (selection.length > 0) {
            var row = selection[0].row;
            var value = data.getValue(row, 0); // Get category name
            alert('You selected: ' + value);
        }
    });
    // ... (chart.draw)
    

    Google Charts provides a robust and well-documented solution for creating data visualizations on the web, especially for those who appreciate its declarative syntax and integration with Google’s ecosystem.

    Leave a Reply

    Your email address will not be published. Required fields are marked *