TechTip: Bar Charts: Generate Professional-Grade Charts in Your Programs in Real Time, Part 2 PDF Print E-mail
Tips & Techniques - Programming
Written by Rafael Victoria-Pereira   
Friday, 13 January 2012 00:00

Support MC Press - Visit Our Sponsors

 

Forums Sponsor

POPULAR FORUMS

Forums

 

 

Search Sponsor

 

POPULAR SEARCHES

Search

This series started with the pie chart, a useful tool that graphically summarizes data. However, pie charts only provide a "snapshot" of a moment. This tip focuses on bar charts, which show the data's evolution.

 

In the previous TechTip, I provided an example of a pie chart similar to the one below, which shows, with a little humor, the most common uses of cell phones:

 

011312RafaelFigure1

Figure 1: This pie chart shows how most people use their cell phones!

 

However, if I wanted to show how those uses evolved through time, it would be impossible to do so with only a pie chart. That's where the Bar Chart API comes in: it provides an easy way to graphically summarize period-related sets of values, as depicted in Figure 2:

 

011312RafaelFigure2

Figure 2: The uses for cell phones have evolved! (Click image to enlarge.)

 

The method used will remain the same throughout the series (read the previous tip before continuing, because I won't explain the methodology in this tip), so let's start by analyzing the template:

 

/$Header

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

  <head>

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>

    <title>

      /%PageTitle%/

    </title>

    <script src="https://www.google.com/jsapi"></script>

    <script>

      google.load("visualization", "1", {packages:["corechart"]});

      google.setOnLoadCallback(drawChart);

      function drawChart() {

        var data = new google.visualization.DataTable();

        data.addColumn('string', 'col1');

/$Column

        data.addColumn('/%ColumnType%/', '/%ColumnTitle%/');

/$TotalRows

        data.addRows(/%TotalRows%/);

/$FirstRow

        data.setValue(/%RowNbr%/, 0, '/%RowTitle%/');

/$Row

        data.setValue(/%RowNbr%/, /%ColNbr%/, /%CellValue%/);

/$Footer

 

        var chart = new google.visualization.BarChart(document.getElementById('chart_div'));

        chart.draw(data, {width: /%width%/,

                          height: /%height%/,

                          title: '/%ChartTitle%/',

                          vAxis: {title: '/%VAxisTitle%/'},

                          hAxis: {title: '/%HAxisTitle%/'}

                         });

      }

    </script>

  </head>

 

  <body>

    <div></div>

  </body>

</html>

 

The Header and Footer sections do basically the same as in the previous tip, but there are a few additional sections. These new sections are directly linked to the way the chart works; while the pie chart needed only two columns (one for the label and the other for the value), here the number of columns must be dynamic, as it depends on the number of different values within each set (the "cell phone uses" in Figure 2). However, the first column is still fixed; it's used to store the label of each value. This is why there are new sections named Column and Total Rows. Just like before, the number of rows is dynamic, but now there are two types of rows; for each set of data (the "cell phone eras" in Figure 2), there's a label (the section FirstRow, which provides the name of the "cell phone era" in Figure 2—Brick-Sized Cell Phones, for instance) and a dynamic number of values (the Row section, which corresponds to the percentages of each cell phone use throughout the "cell phone eras").

 

In order to accommodate these structural changes, the procedure GenBarChart (see QRPGLESRC/GENCHRT in the downloadable source code) also differs a bit from the GenPieChart: there are new entry parameters for the column titles and the vertical and horizontal axis titles. All the other parameters are the same as before, but I've changed some of the names in order to provide independence from the pie chart; check out P_BarRowDS, for instance. In terms of the code itself, the most notable change is related to the rows:

 

       // FirstRow And Row Sections                                       

       For W_RowIdx = 1 to C_BarMaxRows;                                  

         If P_BarRowDS(W_RowIdx).RowTitle = *Blanks;                      

           Leave;                                                         

         EndIf;                                                           

         // Update the Row variables                                      

         updHtmlVar('RowNbr'   : %Char(W_RowIdx-1));                      

         updHtmlVar('RowTitle' : %Trim(P_BarRowDS(W_RowIdx).RowTitle));   

         // Write the FirstRow section                                     

         WrtSection('FirstRow');                                          

         For W_ColIdx = 1 to C_BarMaxColumns;                             

           If P_BarRowDS(W_RowIdx).Cell(W_ColIdx).CellValue= *Zeros;      

             Leave;                                                       

           EndIf;                                                         

           updHtmlVar('ColNbr' : %Char(W_ColIdx));                        

           updHtmlVar('CellValue' : %Char(                                

                       P_BarRowDS(W_RowIdx).Cell(W_ColIdx).CellValue));   

           // Write the Row section                                       

           WrtSection('Row');

         EndFor;                     

       EndFor;

 

Since the P_BarRowDS parameter is now two-dimensional (picture this array as a spreadsheet), I need two cycles to extract all the values from the "cells". The outer cycle checks whether there is data on the row by looking for a title. If a title is found, the section FirstRow is written and the processing continues; otherwise, it leaves the outer cycle and continues to the Footer section. But the title by itself is not enough. I need values. The inner cycle starts by checking whether the "cell" contains a value and leaves the inner cycle if it doesn't, returning control to the outer cycle. If there's a value, then a Row section is written. The rest of the code is similar to the GenPieChart's, with the addition of the Axis Titles. I chose to include these as a reminder of the customization allowed by the Google API. Be sure to read the Configuration Options for more details and customization possibilities.

 

Finally, let's briefly review the TSTGENBAR1 sample program. It generates the bar chart depicted in Figure 2 by filling the P_BarColumnDS and P_BarRowDS parameters values one by one:

 

(…)

Clear P_BarColumnDS;

P_BarColumnDS(1).ColumnType  = 'number';

P_BarColumnDS(1).ColumnTitle = 'Making calls';

(…)

Clear P_BarRowDS;                                

P_BarRowDS(1).RowTitle = 'Brick-sized Cellphones';

P_BarRowDS(1).Cell(1).CellValue = 95;

P_BarRowDS(1).Cell(2).CellValue = 5;

(…)

 

Note that both arrays are being cleared before usage. This is a good practice, because the GenBarChart procedure relies on null values (*Zeros or *Blanks) to determine if there's more data.

 

The next step is invoking the procedure:

 

If GenBarChart(P_PageTitle   : P_ChartTitle :        

               P_BarColumnDS : P_BarRowDS   :        

               P_Width       : P_Height     :        

               P_VAxisTitle  : P_HAxisTitle :         

               P_FileName    : P_ErrorDesc  ) = *Off;

 

This is performed with an IF statement in order to produce the appropriate response: either a Web page with the chart or a message to the user with the description of the error.

 

Naturally, there's plenty of room for improvement, both in the GenBarChart procedure itself and in the sample programs. If you have any doubts or suggestions, feel free to email me!

 

As usual, the complete source code is provided. You can download it here.

 

I hope you enjoyed reading this tip as much as I enjoyed writing it! The next one will cover something completely different but (I hope) equally interesting: the Geo Map API.


Rafael Victoria-Pereira
About the Author:

Rafael Victoria-Pereira is an analyst/developer with 15+ years of IBM i experience. He currently works as a consultant for CPI Consulting in Portugal. His areas of expertise cover IBM i, Lotus Domino/Notes, Javascript, PHP, MySQL, and Python among other programming languages and technologies.

 

MC Press books written by Rafael Victoria-Pereira available now on the MC Press Bookstore.

 

Free-Format RPG IV Flexible Input, Dazzling Output with IBM i
Flexible Input, Dazzling Output (FIDO) is all about interfaces. It shares more with a dog than just its name: it has a few tricks of its own!

List Price $71.95
Now On Sale
 

 

Read More >>
Last Updated on Wednesday, 11 January 2012 12:21
 
User Rating: / 4
PoorBest 
   MC-STORE.COM