TechTip: Pie Charts: Generate Professional-Grade Charts in Your Programs in Real Time, Part 1 Print
Tips & Techniques - Programming
Written by Rafael Victoria-Pereira   
Friday, 23 December 2011 00:00

Support MC Press - Visit Our Sponsors

 

Forums Sponsor

POPULAR FORUMS

Forums

 

 

Search Sponsor

 

POPULAR SEARCHES

Search

A picture is worth 1,000 words. In business, a chart is worth 1,000 rows of data. Learn to create charts in real time, just by pressing a function key. I'll explain how.

 

It's common sense that a well-prepared chart can make a difference when you're trying to prove that the numbers are on your side. From the simplest of charts to the most complex, they all try to provide clarity to the (vast) amounts of data behind them. There are numerous business tools (MS Excel and SAP's Business Object, among others) that are able to generate charts on demand. However, you need to set up a connection or extract the data first. Wouldn't it be nice to see the data on your program's screen and then, just by pressing a key, have it displayed as a chart?

 

What I mean is going from what's shown in Figure 1…

 

122311RafaelFigure1

Figure 1: Here's your dreary green-screen data. (Click images to enlarge.)

 

…to what's shown in Figure 2…

 

122311Rafaelfigure2

Figure 2: The same data looks a lot nicer now!

 

…just by pressing a function key!

 

First, you have to download the CGIDEV2 freeware tool. This is a very powerful tool. Be sure to read the documentation and examples provided. I got to know it as part of the MMAIL, another great tool from easy400.net, which I covered in a previous article.

 

I'm going to use it to generate an HTML file in a process vaguely similar to a MS Word mail merge. So let's move on to the process of generating the pie chart. I'm going to invoke a Google API by creating an HTML file with some code in it to call the API, thus generating the chart. I'll get a nice-looking, interactive pie chart, as shown in Figure 2. I advise you to read the API's documentation, because I won't explain the inner workings of the API in this TechTip.

 

Let's go over Google's example source code:

 

<html>
  <head>
    <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', 'Task');
        data.addColumn('number', 'Hours per Day');
        data.addRows(5);
        data.setValue(0, 0, 'Work');
        data.setValue(0, 1, 11);
        data.setValue(1, 0, 'Eat');
        data.setValue(1, 1, 2);
        data.setValue(2, 0, 'Commute');
        data.setValue(2, 1, 2);
        data.setValue(3, 0, 'Watch TV');
        data.setValue(3, 1, 2);
        data.setValue(4, 0, 'Sleep');
        data.setValue(4, 1, 7);

        var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
        chart.draw(data, {width: 450, height: 300, title: 'My Daily Activities'});
      }
    </script>
  </head>

  <body>
    <div></div>
  </body>
</html>

 

To build a pie chart, I basically need two things: the slice title and the respective value. All those "data.setValue…" lines correspond to the pie's slices. They are going to be the dynamic part of the HTML. Of course, I also need to indicate how many slices my pie will have, so the line "data.AddRows" also needs to be dynamic. Finally, I also want to be able to change the chart's title and dimensions. This last bit is just to give you an idea of what you can customize on the "chart.draw" instruction (read the Configuration Options section of the API documentation for more details). Following CGIDEV2 methodology for HTML creation, I've created a template with three sections: "Header," which will include everything from the beginning of the HTML to the "AddRows…" line; "Row," which is the definition of each slice of the pie chart; and "Footer," for the rest of the html:

 

/$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="http://www.google.com/jsapi"></script>

    <script>

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

    </script>

    <script>

      function drawVisualization() {

        // Create and populate the data table.

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

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

        data.addColumn('number', 'Col2');

        data.addRows(/%TotalRows%/);

/$Row

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

        data.setValue(/%RowNbr%/, 1, /%RowValue%/);    

/$Footer

        // Create and draw the visualization.

        new google.visualization.PieChart(document.getElementById('visualization')).

            draw(data, {width: /%Width%/, height: /%Height%/, title:"/%ChartTitle%/"});

      }

     

 

      google.setOnLoadCallback(drawVisualization);

    </script>

  </head>

  <body style="font-family: Arial;border: 0 none;">

    <div style="width: /%Width%/px; height: /%Height%/px;"></div>

  </body>

</html>

 

Everything you see in the template that starts with /% and ends with %/ is a variable name. The lines starting with /$ mark the beginning of a new section.

 

In order to dynamically generate the proper HTML page with my data in real time, I created an RPG procedure called GenPieChart (see QRPGLESRC/GENCHRT member in the downloadable source code) that receives a few parameters (my data in an array; the page title; the chart's title, width, height, and output file name) and returns a string (used to pass back an error description if something goes wrong). This procedure checks the input parms in routine Init and builds the HTML file in routine Proc. Here's where all the "magic" happens. I start by indicating which template I want to use by invoking the getHtmlIfsMult CGIDEV2 function. Then, the function updhtmlVar is used to replace the /%<variable_name%/ with the data from the entry parameters in order to compose the proper HTML code required to generate the chart. The next step is writing each section to memory. Naturally, I only need to write the Header and Footer sections once, but I'll have to write a Row section for each slice of the pie, or, in other words, for each line of the P_RowDS array. Look at the source code for this particular section:

 

  // Row Section                                          

  For W_Idx = 1 to C_MaxRows;                             

    If P_RowDS(W_Idx).RowTitle = *Blanks;                 

      Leave;                                              

    EndIf;                                                

  // Update the Row variables                             

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

  updHtmlVar('RowTitle' : %Trim(P_RowDS(W_Idx).RowTitle));

  updHtmlVar('RowValue' : %Char(P_RowDS(W_Idx).RowValue));

  // Write the Row section                                

  WrtSection('Row');                                      

  EndFor;                                                 

 

I'm using a For cycle, starting with 1 and ending in 20 (the value of C_MaxRows, which you can change in source member QCPYLESRC/GENCHRT_PR). I'll leave the cycle whenever the current line doesn't have a title, which indicates there's no more data in the array. Be careful with this and always clear the array before use!

 

Then there's a trick: because Google's API expects the values to start at index 0 instead of 1, the RowNbr variable is getting the array position minus 1. After writing each section, it's time to write the file to disk, using the WrtHtmlToStmf(%Trim(W_FileName): 819) instruction, which contains the hardcoded path /GCHARTS/OUTPUT/ and the file name from the P_FileName entry parameter.

 

Note that I'm using hardcoded IFS folder names. Be sure to copy the GCHARTS folder to your IFS and create a share with the same name. Otherwise, you won't be able to display the chart automatically, as shown on the included sample programs (TST_GENPIE and TSTGENPIE1). You can always change this hardcoding to something a bit more dynamic by using a data area for the Template and Output paths. I decided not to do that in order to try to keep the code as simple as possible. However, I used a data area to store the system name (DaSysName), which you'll need to update to run the sample programs.

 

That's it for now. The next TechTip of this series will explore the Bar Chart API and analyze a sample program in more depth. Meanwhile, you can download the source code and the GCHARTS IFS folder for this Tip here .


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 Friday, 23 December 2011 00:00
 
User Rating: / 8
PoorBest 

Related Articles: