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





Search Sponsor




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:



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:



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:



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "">

<html xmlns="">


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




    <script src=""></script>


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


      function drawChart() {

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

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


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




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


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



        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%/'}











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;                      



         // Update the Row variables                                      

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

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

         // Write the FirstRow section                                     


         For W_ColIdx = 1 to C_BarMaxColumns;                             

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



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

           updHtmlVar('CellValue' : %Char(                                


           // Write the Row section                                       





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 Victória-Pereira has more than 16 years of IBM i experience, as a programmer, analyst, and manager. Over that period, he has been an active voice in the IBM i community, encouraging and helping programmers transition to ILE and free-format RPG. Rafael has written more than 50 technical articles about topics ranging from interfaces—the topic for his first book Flexible Input, Dazzling Output with IBM i—to modern RPG and SQL, in his popular RPG Academy and SQL 101 series on He writes in an easy-to-read, practical style that's highly popular with his audience of IBM technology professionals.

Rafael currently works as an Enterprise Architect at the Luis Simões Group in Portugal. His areas of expertise include programming in the IBM i native languages (RPG, CL, and DB2 SQL) and "modern" programming languages, such as C# and Python, as well as project management and consultancy.


MC Press books written by Rafael Victória-Pereira available now on the MC Press Bookstore.


Flexible Input Dazzling Output with IBM i 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



Evolve Your RPG Coding Evolve Your RPG Coding
Evolve Your RPG Coding helps you transition to modern RPG programming, guiding you step by step through ILE and free-format RPG, SQL, and modernization techniques.

List Price $79.95
Now On Sale
Last Updated on Wednesday, 11 January 2012 12:21
User Rating: / 4