<

How to Draw Dynamic Graphs in PHP

A common requirement for business growth is utilizing data to inform strategies and steer data-driven decision-making. Moreover, data visualization tools, like dynamic graphs, enable stakeholders to access and assimilate data in real-time. 

This is because these graphs automatically update themselves every n seconds, without any page refreshes. Although there are numerous PHP chart libraries, very few offer dynamic graphs. 

Hopefully, by the end of this easy tutorial, you’ll know how to draw dynamic graphs in PHP. Plus, you’ll be able to do so in a few minutes.

But before diving into this post’s nitty-gritty, we must define a dynamic PHP chart.

What Are Dynamic Charts/Graphs?

Dynamic charts – also called live charts, data streaming, or real-time charts – are chart types that automatically display updates. Typically, the charts refresh when the server receives new data. 

Hence, there is no need for manual page refreshes, and your users can easily access real-time data. With dynamic graphs, you can rest assured you’re using the most up-to-date data when pursuing data-driven decisions.  

What Are The Steps Of How To Draw Dynamic Graphs in PHP?

As implied earlier, there are different approaches to drawing dynamic graphs using PHP. However, you’ll need to follow these two steps to draw any chart:

  1. Choose the proper PHP chart library.
  2. Leverage your chart library to draw your dynamic graph.

How Can You Choose The Right Chart Library?

Typically, the right chart library would meet your project needs and help you achieve your goals. So, how can you identify what’s best for you? 

First things first, you need to define your project needs. Do you need cross-platform capabilities? What chart types are you looking to implement? 

What reporting features do you need for your web app? Whatever your needs and goals are, you need to define them. This way, you ensure you’re making a chart library decision that suits your project. 

What Are The Steps Of How To Draw Dynamic Graphs In PHP Using FusionCharts?

FusionCharts is a charting library that enables you to create dynamic charts quickly. Its FusionTime solution helps you explore time-series data with limitless interactivity, such as:

  • Time navigator
  • Date range selectors
  • Tooltips with crosslines
  • Interactive legend
  • And more!

Moreover, with a server-side-PHP wrapper, which provides bindings for FusionTime, you can easily add dynamic graphs to any PHP project.

The following are steps to draw dynamic graphs in PHP using FusionCharts:

1) Install PHP-FusionCharts wrapper and FusionTime

Both solutions are distributed along with the FusionCharts Suite. Download and install the FusionCharts library to access the PHP wrapper and FusionTime. 

You can find FusionTime and PHP wrapper installation steps in the docs. 

2) Prepare your data

For this step, let’s assume we’re creating a chart showing “the most populated countries.” The data of various countries and their population is shown in a tabular form below. Note that these are made-up values for this example.

Country Population
Venezuela 290M
Saudi 250M
Canada  180M
USA 130M
UAE 100M

In this case (a single data set), we need a column 2D chart with “countries” along the x-axis and “population” along the y-axis. Here’s how to prepare your data for a single series chart. 

FusionCharts accepts JSON format. So, you can add your data in an index.php file and then convert it to JSON. Here’s the same for our example:

// An array of hash objects which stores data
$arrChartData = array(
    [“Venezuela”, “290”],
    [“Saudi”, “260”],
    [“Canada”, “180”],
    [“USA”, “130”],
    [“UAE”, “100”],
);
$arrLabelValueData = array();
// Pushing labels and values
for($i = 0; $i < count($arrChartData); $i++) {
    array_push($arrLabelValueData, array(
        “label” => $arrChartData[$i][0], “value” => $arrChartData[$i][1]
    ));
}

3) Configure and create your chart

With an extensive library of advanced features, it lets you add rich context to your chart to improve your visualization. Here’s an example of a chart configured to dynamically update chart attributes (chart caption alignment and chart background).

 

Here’s the full code of the above sample:

<!DOCTYPE html>
<?php
    /* Include the `../src/fusioncharts.php` file that contains functions to embed the charts.*/
    include(“../includes/fusioncharts.php”);
?>
<html>
    <head>
        <style>
            .button {
                display:inline-block;
                margin:5px;
                padding: 4px 12px;
                margin-bottom: 0;
                font-size: 14px;
                line-height: 20px;
                color: #333;
                text-align: center;
                text-shadow: 0 1px 1px rgba(255,255,255,0.75);
                vertical-align: middle;
                cursor: pointer;
                background-color: #f5f5f5;
                background-image: -moz-linear-gradient(top,#fff,#e6e6e6);
                background-image: -webkit-gradient(linear,0 0,0 100%,from(#fff),to(#e6e6e6));
                background-image: -webkit-linear-gradient(top,#fff,#e6e6e6);
                background-image: -o-linear-gradient(top,#fff,#e6e6e6);
                background-image: linear-gradient(to bottom,#fff,#e6e6e6);
                background-repeat: repeat-x;
                border: 1px solid #ccc;
                border-color: #e6e6e6 #e6e6e6 #bfbfbf;
                border-color: rgba(0,0,0,0.1) rgba(0,0,0,0.1) rgba(0,0,0,0.25);
                border-bottom-color: #b3b3b3;
                filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=‘#ffffffff’,endColorstr=‘#ffe6e6e6′,GradientType=0);
                filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);
                -webkit-box-shadow: inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);
                -moz-box-shadow: inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);
                box-shadow: inset 0 1px 0 rgba(255,255,255,0.2),0 1px 2px rgba(0,0,0,0.05);
            }
        </style>
        <!- FusionCharts Library ->
        <script type=“text/javascript” src=“//cdn.fusioncharts.com/fusioncharts/latest/fusioncharts.js”></script>
        <script type=“text/javascript” src=“//cdn.fusioncharts.com/fusioncharts/latest/themes/fusioncharts.theme.fusion.js”></script>
        <script>
            changeBackground = function(){
                FusionCharts(“chart-1”).setChartAttribute(‘bgColor’, ‘#efefef’);
            }
            changeCaption = function(e){
                FusionCharts(“chart-1”).setChartAttribute(‘captionAlignment’, ‘left’);
            }
            reset = function(e){
                FusionCharts(“chart-1”).setChartAttribute(‘bgColor’, ‘#ffffff’);
                FusionCharts(“chart-1”).setChartAttribute(‘captionAlignment’, ‘center’);
            }
        </script>
    </head>
    <body>
        <?php
            $chartData = “{ 
                \”chart\”: { 
                    \”caption\”: \”Countries With Most Oil Reserves [2017-18]\”,
                    \”subcaption\”: \”In MMbbl = One Million barrels\”,
                    \”xaxisname\”: \”Country\”,
                    \”yaxisname\”: \”Reserves (MMbbl)\”,
                    \”numbersuffix\”: \”K\”,
                    \”theme\”: \”fusion\”
                },
                \”data\”: [{
                    \”label\”: \”Venezuela\”,
                    \”value\”: \”290\”
                }, {
                    \”label\”: \”Saudi\”,
                    \”value\”: \”260\”
                }, {
                    \”label\”: \”Canada\”,
                    \”value\”: \”180\”
                }, {
                    \”label\”: \”Iran\”,
                    \”value\”: \”140\”
                }, {
                    \”label\”: \”Russia\”,
                    \”value\”: \”115\”
                }, {
                    \”label\”: \”UAE\”,
                    \”value\”: \”100\”
                }, {
                    \”label\”: \”US\”,
                    \”value\”: \”30\”
                }, {
                    \”label\”: \”China\”,
                    \”value\”: \”30\”
                }]
            }”;
            // chart object
            $Chart = new FusionCharts(“column2d”, “chart-1” , “700”, “400”, “chart-container”, “json”, $chartData);
            // Render the chart
            $Chart->render();
        ?>
        <div align=“center” id=“chart-container”>Chart will render here!</div>
            <div>
                <p align=“center” id =“message”></p>
            </div>
            <div id=“controllers” align=“center” style=“font-family:’Helvetica Neue’, Arial; font-size: 14px;”>
                <input type=“button” class=“button” onClick=“changeBackground()” value=‘Change Chart Background’/>
                <input type=“button” class=“button” onClick=“changeCaption()” value=‘Make Caption Text Left Aligned’/>
                <input type=“button” class=“button” onClick=“reset()” value=‘Reset Attributes’/>
            </div>
    </body>
</html>

How Can You Dynamically Update Chart Data?

For real-time data updates, FusionTime uses the FusionCharts#feedData API. This API takes in an array of rows as an optional parameter. 

Note that you must provide an array of rows for the chart to recognize this API. Also, the row must match the schema you provided while creating the chart.

Here’s a sample code:

type Row = Array<number | string>;
declare class FusionCharts {
  feedData(data?: Array<Row>): FusionCharts;
}

 

The above code depicts the addition of new rows using feed data. Your chart will also display these additions according to the time interval you select.

 

Recent Articles

Related Stories

Stay on op - Ge the daily news in your inbox