Chapter 4. Basic Charts

So far, the visualization examples in this book have relied heavily on the GUI interface of various Google applications. Unfortunately, the customization limitations of using only GUI applications quickly become evident. With the Google applications discussed in the previous chapters, Spreadsheets and Fusion Charts, it is fairly simple to create basic graphs and charts. Unfortunately, the sophistication of viewing controls, data source configuration, and even the style of the visualization itself is ultimately limited to the controls presented by default in the application. Apps Script gives some relief to the issue of customization, although limitations of the Apps Script platform impose their own set of limitations. Thus, what is needed is a customizable, feature-rich option, to build on top of the simplistic charts of Spreadsheets and Fusion Tables. The Google APIs, specifically the Visualization (Chart tools) API, are the required building blocks to accomplish this goal.

The world of Google APIs can at first appear somewhat overwhelming. However, the design and methodology behind all Google APIs is strikingly similar. This similarity exists because of an adherence by Google to standard programming elements, as well as existing JavaScript conventions. In addition, Google provides a methodic, nested approach to its API architecture.

Topics covered in this chapter:

  • Crash-course in basic programming concepts
  • Framework of the Visualization API
  • A basic Chart: two methods

Note

Visualization API Reference is available at https://developers.google.com/chart/interactive/docs/reference.

Programming concepts

This section presents a baseline of general programming concepts in an attempt to thwart the confusion of non-programmers while exploring the vast ocean of Google APIs. This brief introduction to programming is by no means a complete or authoritative source for the art that is application programming. Individuals often spend their lives learning the particularities of programming languages; others invest heavily in the improvement of the languages themselves. For the Google Visualization API, a more realistic approach is to provide universal concepts that are inherent in the Google API to developers that have little to no application programming experience. Readers with programming experience may wish to skip this section and go to the Visualization API common Framework section of this chapter.

Variables

Variables are locations in a program designated for storing information temporarily while an application runs. The application is able to access the variable and manipulate its contents. To illustrate, the task of a programming variable is somewhat similar to the aim of a mathematical equation variable. In an equation where 2 + x = 5, the value assigned to the variable x for this instance would be 3. Also, it is worth noting that in this case the value of x will be static. Variables whose purpose is to not change is referred to as a constant variable.

The style used to set variables in Google API code follows this pattern:

varvariable_name = something

Here, the variable_name is a name chosen by the developer and should be representative of the something that's being stored in it.

Tip

Best practice

Use variable names that represent their purpose. For example: a variable name representing an AreaChart API function could be ac, which would be somewhat representative of the variable's purpose (AreaChart). Better yet, assigning a variable name of data for DataTable API function would be more representative. Note that, in general, variables x, y, z are not good representative variable names as it is easy to confuse their purposes in even a small amount of code.

In general, variables have the flexibility to assume various types. Text and numeric values are generic examples. With the Visualization API, the type of variable is automatically detected and generally does not require action on the part of the developer in order to set the correct type.

The various types of variables available in the Visualization API are as follows:

Number

In the programming world there are various types of numbers. In some programming languages, numbers need to be identified by type in the program in order for the program to recognize them properly. For example, the number 2 is an integer, but the number 2.222 is of a type called floating point due to its fraction in decimal format. However, for the general purpose of using the Visualization API, all types of numbers are treated simply as one type. In the previous example, 2 and 2.222 are both simply called numbers in the Visualization API.

Boolean

The concept of a Boolean value is fairly straightforward. A Boolean value can only hold the values "True" or "False". Using a Boolean variable is similar to asking a yes or no question without the ability to accept "maybe" as an answer. In programming practice, Boolean variables are very useful when a condition needs to be tested to be true or false before taking a certain action in the program. How to propose a condition to be tested is covered in the Conditional logic section of this chapter.

Note

The Boolean method of logical decision-making was devised by the mathematician George Boole, and continues to bear his name.

String

A string is exactly as it sounds: it is a collection of characters saved in one variable. Note that characters are not simply A to Z and 0 to 9, but also include punctuation and often other special characters. Similar to number variables, strings can be used to hold information for the application, or store static information to be used by the application. For example, a string containing the characters that spell the word Google would look like this:

string_name = 'Google'

It is important that characters designated to be a single string must be enclosed in quotes. Depending on the specific program method being used, the quotes may be required to be single or double quotes. An example of using a string as a constant label is as follows:

Varname_label = 'Name: '

Here, 'Name: ' could be a field label appearing in an address form application. Note the blank space to the right of the colon. For strings, whitespace is considered a character and may change the expected output of an application if not taken into account.

Also, a variable may be used to store user input as a string. For example, to capture the name entered by a user in an address form application, a variable could be defined as follows:

Var name_field = ''

Notice, in the previous statement there is nothing, not even a whitespace, being stored in the name_field variable. When nothing is assigned to a variable, the variable is considered to have a value of null , or nothing. Giving a variable a value of null is commonly used to set a clean default state. When the application runs, the name_field variable can then be used with confidence to capture user input accurately. Given the variable name of name_field, it would seem that this particular variable is intended to capture name data from a form application.

Tip

Best practice

Remember that whitespace is a character if it is part of a string.

Array

Arrays look a lot like tables, but they are more versatile than a simple table as they can have various dimensions and hold several layers of information. Yet for purposes of the Visualization API, most arrays are generally two-dimensional, thus having the familiar format of columns and rows with single values in the cells. The underlying structure of the Visualization API DataTable function is essentially an array. The DataTable function is used to create a dataset within the API script. For example, the 2010 Chicago Census data from previous chapters can be created completely within the script, and then manipulated by the Visualization API. The following example constructs an array of data using a DataTable helper function called arrayToDataTable(), and consists of several lines of data from the 2010 Chicago Census data.

Array

To reference a specific cell in the data table, a coordinate system is used. For example, to find the number of females that are 20 to 24 years old, matrix coordinates are attached to the data variable.

data[5,2]

It is important to observe that the column and row ranges begin at zero and not with the number one. Also note the entries 'Under 5 years' is in quotes while the other entries are numbers. Arrays can hold a variety of data types; in this specific case, both strings and numbers are contained within a single array.

Equation

Just as in mathematics, equations in Google API applications are a method of performing an operation and equating it to something else. Common mathematical operators (+, -, *, /), as well as Boolean operators (AND, OR, NOT, or alternatively notated as &&, ||, !) can be used.

API call and attributes

Sometimes, when calling the Google APIs, it is helpful to save the resulting value. For example, if data is created or imported it is helpful to have a single name to reference the entire structure of data. Using the 2010 Census data for Chicago, a data array becomes encompassed in a variable through the use of the google.visualization.arrayToDataTable API call. Once the data variable is created, it can be referenced in the same code as an array data[x,y], or simply as data.

var data = google.visualization.arrayToDataTable([['Age', 'Male', 'Female', 'Both Sexes'],
    ['Under 5 years',    94100,       91787,         185887],
    ['5 to 9 years',     84122,       81955,         166077]
]);

Conditional logic

The concept of conditional logic and loops is a natural continuation of the Boolean section discussed previously. Boolean logic is in fact the combination of True or False testing outcomes, also known as conditional logic. To create meaningful logic expressions, the Boolean operators AND, OR, and NOT are introduced. These operators are fairly self-explanatory in that they can be communicated as a sentence in regular language. For example, "If it is sunny AND warm, I will use my air conditioning".

The logical expression, written in pseudo syntax, to which the preceding sentence translates:

If (sunny AND warm) {
airconditioning = true
}

If statements, as seen previously, are to test for a condition. Sunny, as well as warm must be true in order for the preceding condition to be true. The testing result of true assigns air conditioning a value of true. This of course is an over simplification of the power of conditional logic, but does provide basic insight into the thought process. Additional tutorials on this topic can be found on the web.

Functions

Functions are essentially the "guts" of any application, and thus are also at the core of any application using the Google APIs. Rather than writing a program of unorganized components, functions are used to group snippets of code together by functionality. Conceptually, functions are the method a developer uses to create reusable tools. The following is the general structure of a function:

function doSomething () {
// create some variables…

//do some computation…

//return (or not) a result.

}

With the Visualization API, functions are the primary method of encapsulating all of the work that goes into creating the visualization itself.

Tip

Best practice

As with the variables, name functions should be named in such a way that the name is descriptive of the purpose they serve.

Classes (and objects)

Classes have the potential to be a confusing concept, but it also helps to remember the concept of classes in computer programming, which are no different than other areas of study. In biology, a class is part of a hierarchy that is used to define animals. In education, a class is a grouping of students whose learning progress is roughly of the same level (for example, 1st grade, 5th grade, and Kindergarten are all educational class groupings). Therefore, a class in computer programming is a set of instructions for building instances of functions. These instances, that can hold states, are called Objects. When using the Visualization API, requests to the API are formed in such a way as to reflect this hierarchy.

Libraries

In relation to the Visualization API, Libraries are a collection of classes that are used to build applications. Libraries generally consist of commonly used code, such as mathematical functions, that are needed regularly in most applications. Google has opted to call their API Libraries packages. For Google, API packages are the sets of Google objects that allow any programmer a path to manipulating Google's vast infrastructure.

Tip

Best practices

In addition to creating descriptive variable names, there are several additional programming habits that are considered best practice when writing code.

Commenting

The purpose of good commenting practice is to ensure that another developer will be able to determine the purpose of the application without significant forensic efforts. In general, single-line comments are marked by a double forward slash // and blocks of comments are indicated by a forward slash plus asterisks combination /*…*/. It is generally appropriate to provide a block comment at the beginning of a script, application, or even a function. There are a handful of topics that can be included in the comment block:

  • Description of the overall functionality
  • Name/contact information of the author
  • Date of the last update
  • Packages/libraries used
  • Revision number
/* Description: This application draws a bar chart of some data.
Author: Traci Ruthkoski
Date Revised: 9/1/2012
*/

The purpose of single-line commenting is to give short descriptions of a specific line or section of code in order to aid in its readability. However, a potential pitfall when commenting is the overuse of comments, ultimately reducing the readability of the code.

var year='2012';  // Define the year.

Of course, lack of comments does not prevent code from running. The developer must determine the types of comments that are appropriate to their code. Ultimately, commenting is not a requirement but a strongly suggested element of an application, and is often a requirement when publishing applications to Google galleries and forums.

Spacing/format

When writing good code, it is also important to address its readability from a formatting perspective. Just as writing prose requires paragraphs and margins to be read easily, code is more readable when its logical functions are visually segmented. The collection of proper spacing and formatting for a given code language is known as code conventions. The following illustrates a simple framework for detecting an error in an application. Indentation indicates that the error checking statement is encapsulated within the computation of the DrawChart function.

function DrawChart {
     if (something == error) {
          message = 'This app encountered an error!'
     }
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset