29
Fri, Nov
0 New Articles

TechTip: The Tree Map Chart: Generate Professional-Grade Charts in Your Programs, Part 11

General
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

In our ongoing quest to add easy-to-read charts to your documents, this tip introduces yet another type of chart.

 

This series of TechTips has covered a wide range of charts, from the simplest (such as bar charts and line charts) to the most complex (such as the geo chart) and also covered the exotic ones (Piles of Money and Bars of Stuff). This time around, I'll show you the tree map chart, a unique way of representing huge quantities of data in a condensed and structured way. Read on to find out how it works!

The tree map chart is, according to Wikipedia, a way to display hierarchical (tree-structured) data as a set of nested rectangles. Each branch of the tree is given a rectangle, which is then tiled with smaller rectangles representing sub-branches. A leaf node's rectangle has an area proportional to a specified dimension on the data. Often the leaf nodes are colored to show a separate dimension of the data.

When the color and size dimensions are correlated in some way with the tree structure, one can often easily see patterns that would be difficult to spot in other ways, such as if a certain color is particularly relevant. A second advantage of tree maps is that, by construction, they make efficient use of space. As a result, they can legibly display thousands of items on the screen simultaneously.

Google's TreeMap API is quite simple. You provide a data set with three or four columns and as many rows as you want, and it will generate a nice-looking tree map chart. You can customize it quite extensively via the options section. The number of columns is related with the data dimensions the tree map is able to represent. The third column will determine the area of the node's rectangle, while the fourth (if specified) will determine its color. I'll explain the columns' format in greater detail later.

071213RafaelFigure1          

Figure 1: This diagram represents how navigation between layers works.

Figure 1 shows the navigation between layers: the top row of the data table will be presented as the first layer (or level) of the chart. When the user clicks on one of the rectangles that form the layer, the corresponding sub-layer is then displayed. On the example produced by the program TSTTREMAP1, clicking on the "America" rectangle will drill down into the "America" sub-layer, showing rectangles for USA, Mexico, Canada, and Brazil. Right-clicking any of the rectangles takes the user back to the previous level ("Global" in our example). We're using only two levels, but you can add as many as you want.

In order to implement this API, I've created the usual structure: a function to which you pass a set of parameters that include the data table and the chart's options. This function will then merge your parameters with a template to create an HTML file that will be rendered by Google's Tree Map API into a Tree Map.

I really recommend that you read all the previous TechTips of this series, starting with the first one, as well as the Tree Map API documentation because each TechTip highlights an area or detail of the process of generating the charts, and the API's documentation is usually clear and complete. Even though all the chart types are somewhat similar, each of them has its uniqueness.

Let's start with the template (see file TreeMap.tmpl in folder \GCHARTS\TEMPLATES of the downloadable source code at the end of this TechTip):

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

   <script type="text/javascript">

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

   </script>

   <script type="text/javascript">

     function drawChart() {

       // Create and populate the data table.

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

/$Columns

       data.addColumn('string', "/%ColumnTitle1%/");

       data.addColumn('string', "/%ColumnTitle2%/");

       data.addColumn('number', "/%ColumnTitle3%/");

       data.addColumn('number', "/%ColumnTitle4%/");

       data.addRows(/%TotalRows%/);

/$Row

       data.setValue(/%RowNbr%/, 0, "/%CellValue1%/");

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

       data.setValue(/%RowNbr%/, 2, /%CellValue3%/);

       data.setValue(/%RowNbr%/, 3, /%CellValue4%/);

/$OptionsBegin

         var options = {

/$Option

                       '/%OptionTitle%/': /%OptionLongValue%/

/$OptionsEnd

                       };

/$Footer

       // Create and draw the visualization.

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

           chart.draw(data, options);

     }

    

     google.setOnLoadCallback(drawChart);

   </script>

</head>

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

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

</body>

</html>

The template is somewhat similar to the combo chart template. Here, however, there are four columns (two alphanumeric and two numeric), which means the rows will have four cells. This allows you to simultaneously present two values for each row on your data table, or, in other words, two dimensions of your data. Sounds familiar? It should; the first dimension will determine the size of the rectangle, and the second, if specified, will determine the color of the rectangle, as I mentioned before.

The remainder of the template is very similar to the templates presented on previous articles of this series, with the usual header, options, and footer sections.

Each row in the data table describes one node (a rectangle in the graph). Each node (except the root node) has one or more parent nodes. Each node is sized and colored according to its values relative to the other nodes currently shown.

As I've mentioned before, the API expects the data table to have up to four columns (the fourth is optional). These columns should have the following format:

  • Column 0 (string)An ID for this node. It can be any valid JavaScript string, including spaces, and any length that a string can hold. This value is displayed as the node header.
  • Column 1 (string)The ID of the parent node. If this is a root node, leave this blank. Only one root is allowed per treemap.
  • Column 2 (number)The size of the node. Any positive value is allowed. This value determines the size of the node, computed relative to all other nodes currently shown. This value is ignored for non-leaf nodes (it's actually calculated from the size of all its children).
  • Column 3 (optional, number)An optional value used to calculate a color for this node. Any value, positive or negative, is allowed. The color value is first recomputed on a scale from minColorValue to maxColorValue, and then the node is assigned a color from the gradient between minColor and maxColor.

You can find more details about the minColorValue, maxColorValue, minColor, and maxColor in the API's documentation.

Just a side note: if you look at the TSTTREMAP1 source code, you'll see that the first row of that has a 'null' value on column two:

0026.00           P_TreeMapRowDS(1).Cell1 = 'Global';  

0026.01           P_TreeMapRowDS(1).Cell2 = 'null';    

0026.02           P_TreeMapRowDS(1).Cell3 = 0;        

0026.03           P_TreeMapRowDS(1).Cell4 = 0;        

This is the way to indicate the top row of data. Originally, I had the top row as a separate parameter of the function that creates the Tree Map Chart, but I've decided to simplify the source code (and the template) by using this solution. Keep in mind that you'll always need a row that represents the top layer of your chart. For clarity, I've used the first row of data, but the API uses the information on columns 0 and 1 to create the tree structure.

Since I've mentioned the TSTTREMAP1 sample program, let's analyze it briefly.

It starts by retrieving your system's name from a data area. Be sure to fill it in, because without it, the chart's HTML file won't be launched at the end of the program. The next step is to set up the chart's title, size, and file name by assigning values to the P_PageTitle, P_Width/P_Height, and P_FileName parameters, respectively. After that, the program fills the data structures used to hold the chart information itselffirst the columns (P_TreeMapColumnDS) and then the rows (P_TreeMapRowDS), layer by layer. Just one step to go: configuring the options. For that, I've used the P_LongOptionDS introduced in Part 8. I won't discuss the options in detail, and I recommend that you read the respective documentation carefully.

Finally, the function that generates the chart is called and the tree map is displayed on your browser. If it's not, go to the GCHARTS IFS folder and open the file MarketTreeMap.HTML in your browser.

You can download the complete source code here. Feel free to contact me with any questions or suggestions you may have!

Rafael Victoria-Pereira

Rafael Victória-Pereira has more than 20 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 100 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 mcpressonline.com and in his books Evolve Your RPG Coding and SQL for IBM i: A Database Modernization Guide. Rafael writes in an easy-to-read, practical style that is highly popular with his audience of IBM technology professionals.

Rafael is the Deputy IT Director - Infrastructures and Services 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 in "modern" programming languages, such as Java, 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.

Evolve Your RPG Coding: Move from OPM to ILE...and Beyond Evolve Your RPG Coding: Move from OPM to ILE...and Beyond
Transition to modern RPG programming with this step-by-step guide through ILE and free-format RPG, SQL, and modernization techniques.
List Price $79.95

Now On Sale

Flexible Input, Dazzling Output with IBM i Flexible Input, Dazzling Output with IBM i
Uncover easier, more flexible ways to get data into your system, plus some methods for exporting and presenting the vital business data it contains.
List Price $79.95

Now On Sale

SQL for IBM i: A Database Modernization Guide SQL for IBM i: A Database Modernization Guide
Learn how to use SQL’s capabilities to modernize and enhance your IBM i database.
List Price $79.95

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: