Transition animation

Sometimes it is helpful to display two sets of data in animated sequence to illustrate the dynamics of the change in data values. The transition animation option in the Visualization API is intended for that purpose.

Controls for triggering a transition animation utilize standard HTML methods. Common elements, such as a simple button-click using the JavaScript onclick() method, can be used to initiate animation sequences. The following diagram is of the two states of a visualization. In one state, the total population of Chicago taken in the 2000 Census is shown. In the other state, the 2010 Chicago population is visualized. To toggle between the two bar graphs, the user is provided with a button in the upper-right hand corner of the chart. Pressing the button will toggle the visualization between the 2000 and 2010 population chart. Once the button is pressed, the Visualization API will smoothly transition the bar graph to the selected data representation.

Transition animation

The code for the preceding animation requires both basic HTML and Visualization API methods. The HTML method used in this example is button creation via the <form> tag. The behavior of the animation is controlled through Visualization API methods, with the event listener method being particularly useful. At the core, a transition animation must contain the following components:

  • A switching method to switch the current dataset being viewed
  • A user interface mechanism to trigger the switching between datasets

The animated transition code is as follows, with explanations of these key components afterwards.

<!DOCTYPE html>
<html>
  <head>
    <title>Transition Animation Example</title>
  </head>
  <body class="docs framebox_body">

<script type="text/javascript" src="https://www.google.com/jsapi"></script>

<script type="text/javascript">

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

google.setOnLoadCallback(total_population);

function total_population() {
  // 2000 and 2010 Chicago Census Data
  var c2000 = [['Year', 'Total Population'],
                  ['2000', 2895964]];
  var c2010 = [['Year', 'Total Population'], 
                ['2010', 2695598]];

  // Create and populate the data tables.
  var data = [];
  data[0] = google.visualization.arrayToDataTable(c2000);
  data[1] = google.visualization.arrayToDataTable(c2010);
  var options = {
    width: 550,
    height: 350,
    vAxis: {title: "Population"},
    hAxis: {title: "Year"},
    seriesType: "bars",
    animation:{
      duration: 2000,
      easing: 'out'
    }
  };
  
  // initialize current state
  var current = 0;
    // Create and draw the visualization.
  var chart = new google.visualization.ComboChart(document.getElementById('census-visualization'));
  var button = document.getElementById('switch_button'),
  function drawChart() {
     // Disabling the button while the chart is drawing.
    button.disabled = true;
    google.visualization.events.addListener(chart, 'ready',
        function() {
          button.disabled = false;
          button.value = 'Switch to ' + (current ? '2000' : '2010'),
        });
    options['title'] = 'Chicago ' + (current ? '2010' : '2000') + ' Census - Total Population';
    chart.draw(data[current], options);
  }
  drawChart();
  button.onclick = function() {
    current = 1 - current;
    drawChart();
  }
}
</script>
<form><input id="switch_button" type="button" value=""></input></form>
<div id="census-visualization"></div>
</body>
</html>

Programmatic switch

Note that in the preceding code, several distinct features are present which are not found in the general use of the Visualization API. For instance, there are two datasets that are kept in a multi-dimensional table, which is an extension of the array programming method discussed in Chapter 4, Basic Charts.

  var data = [];
  data[0] = google.visualization.arrayToDataTable(c2000);
  data[1] = google.visualization.arrayToDataTable(c2010);

The preceding technique of creating a collection of tables in a single variable simplifies the job of referencing multiple data tables in a single application. Rather than giving each table a variable name, the tables can easily be referenced by indicating their location in the bigger array. For example, to use the Census dataset from 2000 (c2000), simply use the following notation:

data[0]

It is also helpful to note where the c2000 variable came from. In the preceding code, c2000 and c2010 are variables that contain the total population for each respective Census year. Instead of referencing c2000 and c2010 individually, the tables are encapsulated into a more manageable, single array denoted as data[]. The nested array is called a multi-dimensional array .

Tip

Best practice

Use variables to compact datasets into manageable collections, which are called multi-dimensional arrays.

In practice, the technique of creating switchable arrays is useful when having to toggle between drawings using chart.draw(). In the preceding example, current is the variable that tells the chart which dataset to draw.

chart.draw(data[current], options);

The next step is to determine how the current variable is set by user clicks, which behaves as a button toggle.

User interface toggle

The current variable selects the dataset to be visualized. The Visualization API does not provide other interface tools other than special use buttons, so an HTML button must be created for the user interface. Still, beyond the HTML creation, all functionality of the button is handled through Visualization API methods.

Create button

The first task is to create an HTML button with an id tag, similar to how a visualization requires an id for rendering in an HTML framework.

<form>
<input id="switch_button" type="button" value=""></input>
</form>

In the visualization function, create a variable and assign it to the <div id> from the <form> section.

var button = document.getElementById('switch_button'),

This creates a direct link from the HTML button to the visualization code. From this point forward, all button behavior that is related to the chart is defined through the Visualization API.

Button behavior

Given that the button is intended to act as a toggle between Census populations, it is desirable to know the initial state of the button. The current variable is the behavior trigger for the button. For example, if current = 2010, the population for 2010 will be drawn by the visualization. Ideally, the button text Switch to 2000/2010 and visualization never become mismatched. There are several best practices to prevent this issue. The first is to initialize the state of the button to a known value when the application starts. To initialize current, it is assigned an initial value of 0.

// initialize current state
var current = 0;

To prevent mismatched states between the button text and visualized data, the use of a single variable to set the state of the visualization and the button is suggested.

button.value = 'Switch to ' + (current ? '2000' : '2010'),
 });

Note the title is set with the same method so as to keep labeling current for the chart.

 options['title'] = 'Chicago' + (current ? '2010' : '2000') + ' Census - Total Population';

You also have to control button pushes while the chart is drawing. When it is done drawing, it will send out a ready message. An event listener for this message lets the application know when it is ok to accept another button push.

// Disabling the button while the chart is drawing.
 button.disabled = true;
google.visualization.events.addListener(chart, 'ready',
     function() {
       button.disabled = false;

Tip

Best practice

As is the case with programming in general, avoid bugs by properly managing variables. For variables that hold a state, initialize them when the application starts. To prevent mismatched states, try to use only one "variable of truth" to set multiple aspects of the visualization.

Another example of the transition advantages can be viewed when the 2000 and 2010 Census data are placed side by side for one sex. The transition illustrates the difference in growth (or decline) for each of the sexes during each of the Census years.

Button behavior

For the preceding example, the data may be more detailed, but the framework design for the animation remains the same.

Note

Chart transition animation documentation is available at https://developers.google.com/chart/interactive/docs/animation.

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

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