Chapter 5. Formatting Charts

Customization of visualization colors, fonts, views, and other visual attributes add readability and meaning to data displays. In both Spreadsheets and Fusion Tables, the Chart Editor is available in a GUI format, allowing non-programmers to set style choices. The Visualization API presents a larger set of customization options, including style options available through GUI methods. API-based style options include color and font styling, but also include the ability to graphically represent changes in data values through animated transitions. Finally, any style options configured through the Chart Editor in Spreadsheets or Fusion Tables can be set by individual end users by embedding the API Chart Editor component within the visualization itself.

Topics covered in this chapter are as follows:

  • Spreadsheets and Fusion Tables customization
    • Colors and fonts
    • Filters
  • Visualization API
    • Colors, fonts, and labels
    • Axis options
    • DataTable formatters
  • Animated transitions
  • Chart Editor

Regardless of the method used, style options can largely be divided into categories based on the nature of user interaction when viewing the final chart. These style categories are both static and dynamic/interactive.

Static

Static style options are those that are generally not intended for end-user interaction. Fonts, axis labels, colors, and filters fall under the static category. However, many of these options can become interactive as user controls and dashboards are added to the chart.

Spreadsheets

Customizable formatting options for Spreadsheets can be found in the Chart Editor. Instructions on using the built-in Spreadsheets Chart Editor was discussed in Chapter 3, Spreadsheets, Charts, and Fusion Tables. Options to customize the look of the data table itself are found under the Format menu tab. Additionally, the Conditional formatting… option under the Format tab includes conditional logic options similar to those found in any basic spreadsheet application. (Example logic: Color the cell green if value is above 10.)

For Spreadsheets, non-API styling capability does not extend beyond basic spreadsheet logic and Chart Editor options. It is possible to use the Visualization API inside an Apps Script attached to a spreadsheet, but this option is an extension of Spreadsheets and not considered built-in as it is not a GUI capability.

Fusion Tables

Through data filters and views, Fusion Tables offers a slightly more robust formatting option than Spreadsheets. For font and color styling, the Chart Editor is used. Fusion Tables Chart Editor in fact is the same underlying Chart Editor object that also appears as a built-in function to Spreadsheets. Yet in Fusion Tables, the new look version of the application affords additional usability beyond just the Chart Editor. In the newer version, charts are created as tabs and can be kept as a collection. This arranging ability allows for a variety of filters, charts, and views of the same data set to be displayed in one location. Although still in transition at the time of publication, it is expected the new look for Fusion Tables will quickly become the default interface.

The following example is a pie chart created in Fusion Tables using the Chicago 2010 Census data. This chart is a visualization of the male population only, with the slices in hue color representing a subset of larger age groupings. According to the data, Chicago appears to be a young city, with a little over half of its male population under the age of 40 in 2010. Color formatting is a particularly useful added dimension to a chart. Due to this, in the following example, it can be easily determined that 75 percent of the Chicago male population is under 50 years of age, given how the blue and green hues visually represent this population segment.

Fusion Tables

When creating a chart in Fusion tables, it is possible that by default the chart settings may or may not match the expected display for the particular visualization. For example, in order for all segments to be displayed, the preceding pie chart required the slice count to be set from the default to 19, which is the number of age categories in the data set.

Fusion Tables

Tip

Best practice tip

It is always worthwhile to double-check the constraints of the chart type in order to be sure all desired data is accounted for in the graphic.

Chart Editor

To alter the style settings of a visualization in Fusion Tables (New Look), click on the Change appearance… button in the top-right corner of the chart.

Chart Editor

In Fusion Tables, the Change appearance… button is simply an instance of the Chart Editor, with functions described in Chapter 3, Spreadsheets, Charts, and Fusion Tables.

Filters

To create a visualization of a subset of data, Fusion Tables is capable of creating filters. Select the blue Filter drop-down button in the top-left corner of the chart. The drop-down menu will contain the options for the data which can be filtered and displayed. Options available should match the columns in the table. In the following screenshot, the male population of Chicago has been filtered to view only the male population under 50 years of age. It can be noted that the age distribution of the subgroup under 50 years of age is fairly evenly distributed, with the 25 to 29 age group being a few percentages higher than the rest.

Filters

API

The Visualization API offers a significant number of options for style customization. Fine-grained control of color, font, size, and view are possible through the chart.draw() or table.draw() options, as well as through Cascading Style Sheet declaration methods. Special icon graphics are included in tables, in addition to the expected chart color and font styling. These special graphics are called formatters and are provided as an API function.

Colors and fonts: Inline

To provide the style flexibility when setting a table or chart color scheme, the draw() method is used. Both the table and chart draw calls require the data set variable and list of options to be set.

chart.draw(data_variable, options)

Or

table.draw(data_variable, options)

The list of options can be included directly in the draw() line of code, or passed to the call as a variable. The inline option for draw() follows this format:

table.draw(data, {option_name: value})

Where passing a list of options to the draw() method would be as follows:

var options = {
  width: 400,   
  height: 240,   
  title: 'Title of Graph',   
  colors: ['#hex_color1', '#hex_color2', '#hex_color3'] };  

chart.draw(data, options);

To include additional options in the list, simply use a comma between each option. Regarding option availability, the type of chart determines each chart's options. Documentation for option formatting can be found with the corresponding chart type documentation on the Google Chart Tools Developers web page.

Note

You can find more information about Google Chart Developers at https://developers.google.com/chart/.

Colors and fonts: Inline

Finally, to recreate the pie chart of Chicago's 2010 male population shown earlier in this chapter using the API, the following formatting information would be used. Note the DataTable has been omitted, as it remains identical to previous examples but would be required for a complete recreation of the chart rendering.

new google.visualization.PieChart(document.getElementById('visualization')).
  draw(data, {

    title:"Chicago Male Population by Age - 2010 Census",
    titleTextStyle: 
    {color: #635A5E, fontName: 'cursive', fontSize:  25},  
    colors:
['#84160C', '#CC0000', '#E06666', '#E69138', '#F6B26B', '#F1C232', '#FFD966', '#A64D79', '#C27BA0', '#674EA7', '#8E7CC3', '#3C78D8', '#6D9EEB', '#3D85C6', '#6FA8DC', '#6AA84F', '#93C47D', '#B6D7A8', '#A2C4C9'], 

is3D:true,

reverseCategories:true

});

Colors and fonts: Cascading Style Sheets

Style options for a table can also be set using Cascading Style Sheets. The style definitions using CSS within the API script follow the same conventions as with HTML. The defined CSS styles are then grouped together by creating a variable that holds the information matching a CSS style to a specific table component.

<style type='text/css'>
  .table-color {
    color: #635A5E;
  }

  .big-font {
    font-size: 25px;
  }

  .header-font {
    font-style: cursive;
  } 

</style>

. . .


var cssClassNames = {
  'headerRow': 'big-font header-font', 
  'tableRow': 'table-color'
  };

var options = {'cssClassNames': cssClassNames};

Finally, the table.draw() call uses the options variable by effectively passing the CSS information along to the visualization draw() method.

Note that it also follows that charts are theoretically able to inherit styles from CSS files given their adherence to framework standards, of course assuming the chart itself allows the configuration.

Views

Regardless of the size of a dataset, it may be desirable to only show a portion of the data in a particular chart. The Visualization API offers a method to create data-targeted charts by using the DataView class. Additionally, Data Views are nested and thus provide the ability to create views from other views. Through the DataView class, it is also possible to create different styles of horizontal and vertical axes.

Using DataView

DataView does not change data values, but instead designates which columns are to be viewed in the chart. It is also possible to specify particular rows as viewable. Both row and column views can be set manually by designating them directly in the view, or programmatically through other decision processes. The following example is a view intended to only show the age group categories and corresponding population numbers for males from the 2010 Chicago Census data. The code for creating and drawing the view itself is included here, but note in the live example the data in DataTable does not change in order to create the view.

// Make a view of only age groups and males
var dataView = new google.visualization.DataView(data);
dataView.setColumns([0,1]);
// Draw a table with the new view
var table = new google.visualization.Table(document.getElementById('table'));
table.draw(dataView, {width: 400, height: 200});
// Draw a chart with the new view
var chart = new google.visualization.ColumnChart(document.getElementById('chart'));
chart.draw(dataView, {width: 400, height: 200});

Here we designated the columns to be viewed by using the setColumns function of DataView and set the configuration to a variable. Next, the new variable containing the view information is used to create a chart. In the preceding code snippet, the new view, dataView, is used to create a table in addition to a chart. The titles of the new view are defined as ordinary HTML. The resulting visualization is as follows:

Using DataView

Axes options

For both horizontal and vertical chart axes, there are several basic customization options. Just as with other chart customizations, the axes are modified through the chart.draw() function. To modify the horizontal axis, the hAxis option of chart.draw() is used. Similarly, to format the vertical axis, vAxis of chart.draw() is implemented. For example, in order to set the horizontal axis title to "Age Groups" on the Census Area Chart, the following option would be listed in the AreaChart.draw() function:

hAxis: {title: 'Age Groups'}

To discuss advanced axis options, it is important to first understand several terms associated with axes. Firstly, axes can be defined as discrete or continuous. A discrete axis is one that has values that are defined into categories or groups. These groups are also evenly spaced. The Chicago Census data has a column of a series of age groups, which is interpreted as a discrete axis. A continuous axis has an infinite number of values. The population number axis of the Chicago Census is considered a type of continuous axis in this case, even though its values (population) are not truly infinite.

In addition to being either discrete or continuous, an axis can be either major or minor. A major axis is the natural interpretation of the chart. In the Chicago Census example, the age groups make up the major axis because the age groups are the intended primary focus relative to the population count. A minor axis is the secondary element in the graph, in this case being the population per age category. Finally, while the major axis is more likely to be the horizontal axis, this is not necessarily always the case. Other rules to know regarding major/minor and discrete/continuous axes are as follows:

  • The major axis can be horizontal or vertical
  • The major axis can be discrete or continuous
  • The minor axis is always continuous

Most axis settings will conform to the type of chart and data represented. However, it is possible to control the type of major axis through the dataView.SetColumns attribute, which was previously used in this chapter to set views. To make an axis discrete, set the type to string inside the dataView.SetColumns attribute.

// Set column 1 to be string
dataView.SetColumns([1, type: 'string' ]);

To convert a discrete axis to continuous, set the type to number, date, datetime, or timeofday.

Note

The Axes Options documentation is available at https://developers.google.com/chart/interactive/docs/customizing_axes.

DataTable formatters

Formatters are special functions provided by the API that insert graphic representations into a table visualization. There is a handful of formatters available:

  • Arrow
  • Bar
  • Color
  • Date
  • Number
  • Pattern

All formatters follow the same method as other API calls, with the formatter name followed by its options. The following line creates the formatter object:

google.visualization.formatter_name(options)

Formatters only affect one column at a time. To format multiple columns, use multiple formatter calls. The following line applies the formatter to the second column in the data table (first column is 0):

Formatter_name.format(data, 1);

In addition, formatters require that the AllowHTML option from table.draw() is set to true. This requirement is due to the fact that formatters are rendered as HTML, and thus HTML must be allowed in the table in order to be viewed properly.

In summary, the process for using a formatter is as follows:

  1. Create the data table.
  2. Create formatter(s).
  3. Apply formatter(s) to a column(s).
  4. Draw the table.

Note

Formatters can only be used with DataTable and not DataView as DataView is read-only.

Arrow

The arrow formatter creates arrow icons next to values in the table. The arrow is green and points upward when the value in the table cell is above a certain value. Similarly, the arrow is red and points downward when the cell value is below a certain threshold. If the value is equal to the threshold value, no arrow is displayed.

In the following example, the threshold value is set to 0, which is also the default.

Arrow

To change the threshold value, use the base option available for TableArrowFormat. The following line sets the threshold for comparison to a value 12.

var formatter = new google.visualization.TableArrowFormat({base: 12});

Bar

The bar formatter creates a bar-shaped visualization of the value in an adjacent column in the table. Just as with arrow formatters, bar formatters are also able to receive options at the time the formatter object is created. In the following example, a bar formatter is created for the male, female, and total population columns of the Chicago Census 2010 data. A new formatter must be created for each column. The bar colors, size, and maximum value are set using the formatter options available through the API.

<!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>Google Visualization API Sample</title>
  <script type="text/javascript" 
  src="http://www.google.com/jsapi"></script>
  <script type="text/javascript">
    google.load('visualization', '1', {packages: ['table']});
    function drawVisualization() {
      // Create and populate the data table.
      var data = google.visualization.arrayToDataTable([
        ['Age', 'Male', 'Female', 'Both Sexes'],
        ['Under 5 years',     94100,    91787,      185887],
        ['5 to 9 years',      84122,    81955,      166077],
        ['10 to 14 years',    83274,    81192,      164466],
        ['15 to 19 years',    91528,    91405,      182933],
        ['20 to 24 years',    108407,   114620,     223027],
        ['25 to 29 years',    134931,   141208,     276139],
        ['30 to 34 years',    119828,   119584,     239412],
        ['35 to 39 years',    100651,   99857,      200508],
        ['40 to 44 years',    89957,    87674,      177631],
        ['45 to 49 years',    85645,    86217,      171862],
        ['50 to 54 years',    80838,    86037,      166875],
        ['55 to 59 years',    68441,    76170,      144611],
        ['60 to 64 years',    54592,    63646,      118238],
        ['65 to 69 years',    37704,    47366,      85070],
        ['70 to 74 years',    27787,    38238,      66025],
        ['75 to 79 years',    20448,    30252,      50700],
        ['80 to 84 years',    14637,    24467,      39104],
        ['85 to 89 years',    7842,     16548,      24390],
        ['90 years and over', 3340,     9303,       12643]
      ]);
    
    // Create and draw the visualization.
    var table = new 
    google.visualization.Table(document.getElementById
    ('visualization'));
    
    // Create formatters for each column
    var formatter_male = new 
    google.visualization.TableBarFormat({width: 200, 
    colorPositive: 'blue', max: 276139});
  
    var formatter_female = new 
    google.visualization.TableBarFormat({width: 200, 
    colorPositive: 'blue', max: 276139});
  
    var formatter_both = new 
    google.visualization.TableBarFormat({width: 200, 
    colorPositive: 'green', max: 276139});
      
    // Apply formatter to male, female, & both sexes columnsformatter_male.format(data, 1); 
      formatter_female.format(data, 2);  
      formatter_both.format(data, 3); 

      table.draw(data, {allowHtml: true, 
      alternatingRowStyle: true});
    }
    
    google.setOnLoadCallback(drawVisualization);
  </script>
</head>
<body style="font-family: Arial;border: 0 none;">
<div id="visualization" style="width: 1200px; height: 500px;"></div>
</body>
</html>

The following is the resulting visualization from the preceding example code:

Bar

Color

The color formatter allows the developer to programmatically set color values for cells in a table visualization. Similar to the capabilities of general spreadsheet applications, cells can also be set to vary in color depending on an assigned mathematical condition. For example, in the following snippet of a table containing the Chicago Census 2010 data, the color of the cell is red with a white font if the number of individuals in that particular group is between 0 and 10000. The same cell is formatted orange with a white font if the number of individuals is between 10001 and 99999.

Color

Date

To display a date in a table, use the DateFormat formatter. The DateFormat Formatter has three options: short, medium, and long. The format option type is set at the time of the creation of the formatter.

var formatter = new google.visualization.DateFormat({formatType:'medium'});

The short, medium, and long types refer to the style in which the date is displayed. The short format is represented only with numbers and the year is truncated to two digits. The medium format uses all four digits of the year and provides the name of the month in its abbreviated form. The long format is the same as the medium format, but the name of the month is spelled out in its entirety.

Date

Number

To indicate special formatting for numbers, the number formatter is used. In the following example, the font color is set based on a positive or negative numerical value.

Number

The number formatter can also be set to indicate a prefix or suffix symbol and provide parentheses for negative values. Formatting is set in a similar manner to other formatters using the options method.

var formatter = 
new google.visualization.TableNumberFormat(
    {prefix: "$", negativeColor: 'red', negativeParens: true});

Pattern

The purpose of a pattern formatter is to condense two columns of information into a single column for display. This method is particularly useful when creating a table of URL links or mailto links. To create a table with a pattern formatter, select two columns to condense as a display. In the following example, the website name's column and corresponding URL's column are condensed to produce a live link for each site.

Pattern

The previous sample was created from the following code:

// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
    ['US Census Bureau Links', 'URL'],
    ['Home Page', 'www.census.gov/'],
    ['Research Matters Blog', 
    'researchmatters.blogs.census.gov'],
    ['Random Samplings Blog', 'blogs.census.gov'],
    ]);

// Create and draw the visualization.
var table = new google.visualization.Table(document.getElementById('visualization'));

var formatter = new google.visualization.TablePatternFormat('<a href="http://{1}">{0}</a>'),

formatter.format(data, [0, 1]); // Apply formatter and set the formatted value of the first column.

var view = new google.visualization.DataView(data);
  
view.setColumns([0]); // Create a view with the first column only.
table.draw(view, {allowHtml: true});

Note

A live example is available at http://gvisapi-packt.appspot.com/ch5-examples/ch5-pattern.html.

You can find more information about Formatter Documentation at https://developers.google.com/chart/interactive/docs/reference#formatters.

Paging

Formatting a table into pages is a common practice when a long list of data needs to be presented in a small amount of space. The DataTable object allows for the enabling and customization of paging on table renderings. To convert a basic table into a paged table, add the following option to the table.draw() call.

page: true

Paging configurations may also be further customized. The full API request with the option to restrict the number of items per page to 5 is as follows:

table.draw(data, {allowHtml: true, page: 'enable', pageSize: 5});

Additional format settings can also be included in the options list, including how many rows to display per page (pageSize), the page to display by default (startPage), and paging icons or text to replace the default arrow buttons (pagingSymbols).

Paging
..................Content has been hidden....................

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