How Can I Display Data in a Google Column Chart with Dynamic PHP Values?

Understanding the Original Code

Hey there! Today, I’m going to help you navigate through embedding a Google Chart into your webpage using dynamic values from PHP. This is quite common when you want to visualize data that comes from a database or another data source in real-time. Let’s break down the provided code snippet and understand what’s happening step by step.

Here’s a look at the original script you posted:

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
    google.charts.load("current", {packages:['corechart']});
    google.charts.setOnLoadCallback(drawChartaccom);
    
    function drawChartaccom() {
        var data = google.visualization.arrayToDataTable([
            ["Element", "Density", { role: "style" }],
            ["Strongly Disagree", <?= number_format($accomasd, 2); ?>, "#689df6"],
            ["Disagree", <?= number_format($accomad, 2); ?>, "ee695d"],
            ["Agree", <?= number_format($accomaa, 2); ?>, "fcc936"],
            ["Strongly Agree", <?= number_format($accomasa, 2); ?>, "color: #34a853"],
            ["Main", <?= number_format($accomf, 2); ?>, "color: #ff6d01"]
        ]);

        var view = new google.visualization.DataView(data);
        view.setColumns([0, 1, { 
            calc: "stringify", 
            sourceColumn: 1, 
            type: "string", 
            role: "annotation" 
        }, 2]);

        var options = {
            title: "III. ACCOMMODATIONS",
            height: 500,
            bar: {groupWidth: "95%"},
            legend: { position: "none" },
        };
        
        var chart = new google.visualization.ColumnChart(document.getElementById("accom"));
        chart.draw(view, options);
    }
</script>

What This Script Does

  1. Loading the Google Charts Library:

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

This line ensures that the Google Charts library is loaded, which is necessary for drawing the chart.

  1. Setting Up the Callback to Draw the Chart:

google.charts.load("current", {packages:['corechart']});
   google.charts.setOnLoadCallback(drawChartaccom);

Here, we’re loading the specific “corechart” package and setting a callback function (drawChartaccom) to run once the chart library is loaded.

  1. Defining the drawChartaccom function:

function drawChartaccom() {
       var data = google.visualization.arrayToDataTable([
           ["Element", "Density", { role: "style" }],
           ["Strongly Disagree", <?= number_format($accomasd, 2); ?>, "#689df6"],
           ["Disagree", <?= number_format($accomad, 2); ?>, "ee695d"],
           ["Agree", <?= number_format($accomaa, 2); ?>, "fcc936"],
           ["Strongly Agree", <?= number_format($accomasa, 2); ?>, "color: #34a853"],
           ["Main", <?= number_format($accomf, 2); ?>, "color: #ff6d01"]
       ]);

This part creates a DataTable using the arrayToDataTable method. The data values within <?= number_format($accomasd, 2); ?>, <?= number_format($accomad, 2); ?>, etc., are dynamically populated using PHP.

The number_format function ensures that these values are formatted to two decimal places before being passed to the JavaScript. This is a critical step to ensure the data is accurate and properly formatted.

It’s important to note that colors for “Agree” and “Main” have missing a # sign in "ee695d" and "fcc936", while “Strongly Agree” and “Main” are correctly formatted with color: #34a853 and color: #ff6d01.

  1. Creating a Data View and Customizing the Columns:

var view = new google.visualization.DataView(data);
   view.setColumns([0, 1, { 
       calc: "stringify", 
       sourceColumn: 1, 
       type: "string", 
       role: "annotation" 
   }, 2]);

This code customizes the data view by adding annotations, effectively making the density values also appear on the bars.

  1. Chart Options and Drawing the Chart:

var options = {
       title: "III. ACCOMMODATIONS",
       height: 500,
       bar: {groupWidth: "95%"},
       legend: { position: "none" },
   };
   
   var chart = new google.visualization.ColumnChart(document.getElementById("accom"));
   chart.draw(view, options);
   }

Finally, we set various chart options like the title, chart height, bar width, and legend position. Then, we initialize the chart by drawing it in the HTML element with id="accom".

Fixing and Improving the Script

Now, let’s fix the few issues and make sure everything runs smoothly:

  1. Ensure color formats are consistent by adding a # to “Disagree” and “Agree” color codes.
  1. Confirm that the PHP variables ($accomasd, $accomad, etc.) are correctly defined and have values.

Here’s the improved script:

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
    google.charts.load("current", {packages:['corechart']});
    google.charts.setOnLoadCallback(drawChartaccom);
    
    function drawChartaccom() {
        var data = google.visualization.arrayToDataTable([
            ["Element", "Density", { role: "style" }],
            ["Strongly Disagree", <?= number_format($accomasd, 2); ?>, "#689df6"],
            ["Disagree", <?= number_format($accomad, 2); ?>, "#ee695d"],
            ["Agree", <?= number_format($accomaa, 2); ?>, "#fcc936"],
            ["Strongly Agree", <?= number_format($accomasa, 2); ?>, "color: #34a853"],
            ["Main", <?= number_format($accomf, 2); ?>, "color: #ff6d01"]
        ]);
        
        var view = new google.visualization.DataView(data);
        view.setColumns([0, 1, { 
            calc: "stringify", 
            sourceColumn: 1, 
            type: "string", 
            role: "annotation" 
        }, 2]);

        var options = {
            title: "III. ACCOMMODATIONS",
            height: 500,
            bar: {groupWidth: "95%"},
            legend: { position: "none" },
        };
        
        var chart = new google.visualization.ColumnChart(document.getElementById("accom"));
        chart.draw(view, options);
    }
</script>
<div id="accom" style="width: 100%; height: 500px;"></div>

By ensuring that color formats are correct and fixing any potential issues with PHP variable values, this script should now be able to render a dynamically populated Google Column Chart on your webpage.

It can feel a bit overwhelming at first, but breaking it down step by step can make it much more manageable. Happy coding!


Comments

Leave a Reply

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