Introduction
Hierarchical data, such as organizational charts and taxonomies, are good candidates for visualization. Because there is a clear organizational structure to the data, it is possible to lay out the information such that the hierarchy is clear to the user, with directionality implied by the position of the nodes. Thinkmap offers two layouts, the tree layout and the radial layout, that are specifically designed for hierarchical information.
In this tutorial, we show how to implement these layouts and how to customize them to show the hierarchy as either as top-down or left-to-right.
Thinkmap models hierarchical data using trees. A tree is a special kind of graph in which all nodes are descended from a single root node. The root node has no parent, and every other node has exactly one parent. Trees are used to back the treeLayout and the radialLayout, and determine the position of each node relative to its parent.
Getting Started
If you view the source of this page, you can see the code that makes up this example in its entirety, but we'll go through it section-by-section here.
If you view the source of this example, you will notice that we are linking to two important source files:
The first file is the thinkmap.js file for your project. The second file orgchart.js contains
the code for this example, which we will now discuss.
A Server-side Flatfile Datasource
This example uses a server-side flatfile data source. The server side flatfile structure is ideal for situations in which you have a lot of data, but that data does not change often. The data sits on the server, and is loaded to the client as necessary, based on how the client queries the data.
The server-side flatfile data source is also an ideal way to prototype if you know that you will be connecting to a database at a later time. The syntax and structure of the server configuration file, server.tas, is very similar whether you are using a flatfile datasource or a database datasource. This way you can start working with Thinkmap from an export from your database, and not worry about the actual connection to the database until you are ready to deploy.
We're going to start by describing how the datasource works, and then take a look at the client code.
Take a look at the file directory of this tutorial. If you visit the initial welcome page of the Thinkmap server
(typically at http://localhost:8080/), you can find the directory where this tutorial was installed to by looking under the folder location
for the project. For instance: C:\Users\johndoe\thinkmapprojects\treetutorial
Upon opening this directory, you should see a couple of files that are different from a client only version of Thinkmap. The first is the server.tas file.
This file contains information as to how to map your flat files to Thinkmap nodes and edges that will appear on the client.
In addition to the server.tas file, there is a WEB-INF folder that contains a series of jars and a web.xml file. The jars represent
files necessary for the server to run and include thinkmapserver.jar, and lucene.jar. Finally, the web.xml file, a requirement
for any server based Java application, handles the server mapping for the Thinkmap server and is typically not modified.
At this point, we should also mention the tas_status page, which serves as a status page for a Thinkmap Server. Here you can view
the status of any datasources you have running on the client and is a great place for tracking down errors, restarting datasources, and building indexes.
The tas_status page for this project can be viewed here
Defining Metadata
In server.tas, you define your nodes and edges.
Individual nodes and edges are Entities and a category of nodes or edges is an EntityType. There are two EntityTypes that are automatically created, called node and edge. You need to define the other EntityTypes for your particular application, which will be sub-types of node and edge.
Let's get started with defining nodes
Defining Nodes
Each EntityType should get its data from one flat file. When you define a node, you will need to
- Choose a name for the EntityType.
- Give the path to the flatfile which contains its data.
- Specify the columns of the table that will be used to get data.
- Specify one or more columns as "key" columns that will be used to uniquely identify each Entity in the EntityType.
Let's look at our node definition for the employee EntityType.
<!-- define an employee node entity type -->
<node name="employee" table="data/employees.csv" >
<column name="employeeid" type="Integer" property="true" key="true"/>
<column name="name" type="String" property="true"/>
<column name="jobtitle" type="String" property="true"/>
<column name="gender" type="String" property="true"/>
<column name="program" type="String" property="true"/>
<column name="department" type="String" property="true"/>
<column name="mgrid" type="Integer" property="true"/>
<column name="lastname" type="String" property="true"/>
<column name="firstname" type="String" property="true"/>
<column name="companydt" type="Date" property="true" dateFormat="MM/dd/yyyy" />
<column name="birthdate" type="Date" property="true" dateFormat="MM/dd/yyyy"/>
</node>
The name of the entityType is employee, it's pulled from the flatfile at data/employees.csv, it's key is in the first column, and there are a number of properties that we bring in.
Let's look at our edge definition for the manageremployee EntityType
<edge name="manageremployee" table="data/employees.csv" from="employee" to="employee" bidirectional="false" >
<column name="employeeid" type="Integer" bindTo="to" bindColumn="employeeid" />
<column name="name" type="String" property="false"/>
<column name="jobtitle" type="String" property="false"/>
<column name="gender" type="String" property="false"/>
<column name="program" type="String" property="false"/>
<column name="department" type="String" property="false"/>
<column name="mgrid" type="Integer" bindTo="from" bindColumn="employeeid" />
<column name="lastname" type="String" property="false"/>
<column name="firstname" type="String" property="false"/>
<column name="companydt" type="Date" property="false" dateFormat="MM/dd/yyyy"/>
<column name="birthdate" type="Date" property="false" dateFormat="MM/dd/yyyy"/>
</edge>
Note that we've set bidirectional="false". This indicates that the edges of a manageremployee relationship
only go from manager to employee (and not the other way around).
The Client Side Code
Let's examine the treetutorial.js. We're going to focus on the
parts of the code that are pertinent to displaying hierarchical data.
In the example, we allow the user to switch from one type of layout to another. In order to do so, we need to rotate the components of each entity so that the text is pointing in the right direction, depending on the type of layout. To lay the groundwork for this, we add a class, 'rotatable', to the elements that we want to rotate.
// Set up the template used to display employees. In addition
// to the definition here, other elements of the look and feel are set
// in the CSS definitions for node in the index.html file.
display.template('employee').as(function(selection,e) {
selection
.append('rect')
//we add the class rotatable so that we can act on both the
//rect and the text svg
.addClass('rotatable')
.attr("width","6px")
.attr("height","6px")
.attr("x","-3px").attr("y","-3px");
selection.append('text').addClass('rotatable')
.attr("dy","4px")
.attr("dx","8px")
.text(e.data.name);
});
We then create two trees, one for ancestors (which in this case corresponds to managers), and another for descendants (which corresponds to reports), so that ancestors and descendants can be laid out separately. This is especially important when we have an overlapping hierarchy (when at least one node has two parents). This is not the case with our data here, but if you adapt this example to data that has overlapping hierarchy, the two-tree layouts will work well.
// Create a tree for ancestors (managers).
var ancestorTree = new thinkmap.graph.Tree();
// Create a tree for descendants (reports).
var descendantTree = new thinkmap.graph.Tree();
We create the layouts that will be used to lay out the trees. We have two tree layouts (one for ancestors, and one for descendants), and two radial layouts. The descendant tree layout is configured to handle the angled text.
// Create a layout for ancestors
var ancestorTreeLayout = thinkmap.layout.treeLayout(display)
.tree(ancestorTree) // backed by the ancestor tree
.spacing(-150); // with negative spacing
// Create a layout for descendants
var descendantTreeLayout = thinkmap.layout.treeLayout(display)
.tree(descendantTree) // backed by the descendant tree
.spacing(150) // with positive spacing
// the bbox option returns a rectangle that is used to position the
// entities in the layout. It defaults to the actual bbox of the
// entity (the rectangle that encloses the entity)
.bbox(function(node){
// if we have an up-down tree, return a rectangle that allows
// for space for diagonal text. If we returned the actual
// bbox the spacing would be more than we needed.
if (directionSelect.value=='y' && descendantTree.root() != node) {
return {x:-13,y:-13,width:26,height:26};
} else {
// Otherwise return the actual bbox.
return display.bbox(node);
}
})
.margin(2); // puts a little space between each node
var ancestorRadialLayout = thinkmap.layout.radialLayout(display)
.tree(ancestorTree) // backed by the ancestor tree
// set the minimum spacing (radial distance from one depth to the next)
.spacing(150)
// set the opening angle of the radial display
.angle(function() { return directionSelect.value=='x' ? 180 : -90;})
// set the number of degrees available to the layout
.opening(60);
var descendantRadialLayout = thinkmap.layout.radialLayout(display)
.tree(descendantTree) // backed by the descendant tree
// set the minimum spacing (radial distance from one depth to the next)
.spacing(150)
// set the opening angle of the radial display
.angle(function() { return directionSelect.value=='x' ? 0 : 90;})
// set the number of degrees available to the layout
.opening(300);
When we query our graph, we put the entities in the appropriate tree. Each query adds data to both the display and the appropriate tree.
// Calling center centers the graph based on an entity, adding additional
// entities as necessary.
function center(entity) {
// add the entity to the display
display.add(entity);
ancestorTree.root( null ); // Clear the ancestor tree.
ancestorTree.root( entity ); // Make the entity the root of the tree.
descendantTree.root( null ); // Clear the descendant tree.
descendantTree.root( entity ); // Make the entity the root of the tree.
// a "future" graph that contains a graph with descendant entities
var descendantQuery = graph.query(
// return node, node-edge-node, and node-edge-node-edge-node
// paths
['node',['edge','node',[0,2]]]
)
// in the direction specified in server.tas
// (from manager to employee)
.direction(thinkmap.graph.Edge.OUT)
// starting with the entity
.execute( entity )
// as each traversal path is returned
.onresult(function(r){
// add the path to the descendant tree.
r.addToTree(descendantTree);
// add the entities from the traversal path to the display.
display.add(r);
// layout the display incrementally
display.layout();
});
// a "future" graph that contains a graph with ancestor entities
var ancestorQuery = graph.query(
// return all node-edge-node paths
['node',['edge','node',[0,-1]]]
)
// in the opposite of the direction specified in server.tas
// from employee to manager
.direction(thinkmap.graph.Edge.IN)
// starting with the entity
.execute( entity )
// as each traversal path is returned
.onresult(function(r){
// add the path to the ancestor tree.
r.addToTree(ancestorTree);
// add the entities from the traversal path to the display.
display.add(r);
// layout the display incrementally
display.layout();
});
When both queries are complete, we remove any items outside the queries from the display, and also fix the rotation of the text (depending on the position of the entity and the pulldown menus)
// combine the descendantQuery and ancestorQuery futures
thinkmap.async.all(descendantQuery,ancestorQuery)
// after they are fulfilled
.then(function(d,a) {
// Make a selection which is the union of both graphs.
var union = display.select(d).union(display.select(a));
// Remove any other entities from the display.
display.retainOnly(union);
// Add a listener to 'layout' which will be called exactly
// once after the layout lays out the entities.
display.once('layout',function() {
fixRotations();
// Smoothly scroll the display
display.transition().scrollTo(
// The center of the display will be the position
// of the root of the descendant tree after the
// layout finishes animating.
activeLayout.targetPosition( descendantTree.root() )
);
});
// Cause the layouts to lay out the entities.
display.layout();
});
When the user changes a pull down menu, we turn on the appropriate layouts, and rotate the text as necessary.
function changeLayout(){
// the current value of the direction pull down menu ('x' or 'y')
var axis = directionSelect.value;
// Set the axes of the two tree layouts.
ancestorTreeLayout.axis(axis);
descendantTreeLayout.axis(axis);
// a display selection of all nodes of type 'employee'
var employees = display.select('employee');
// if the tree pull down menu is radial
if (treeSelect.value=='radial') {
// Remove the rotation of all rotatable elements ('text' and 'rect')
// from employees.
employees.elements().selectAll('.rotatable').attr('transform',null);
// disable the tree layouts
descendantTreeLayout.enabled(false);
ancestorTreeLayout.enabled(false);
// enable the radial layouts
descendantRadialLayout.enabled(true);
ancestorRadialLayout.enabled(true);
// make the active layout (used for positioning the display)
// the radial layout
activeLayout = descendantRadialLayout;
// use curved edges optimized for the x direction.
display.template('edge').as(
thinkmap.display.edgestyle
.curved().axis('x')
);
display.once('layout',fixRotations);
display.layout();
} else { // the tree pull down menu is tree
// Remove the rotation on all employees. The rotation
// was set by the radial layout.
employees.transition().rotation(0);
// disable the radial layouts
ancestorRadialLayout.enabled(false);
descendantRadialLayout.enabled(false);
// enable the tree layouts
ancestorTreeLayout.enabled(true);
descendantTreeLayout.enabled(true);
// make the active layout (used for positioning the display)
// the tree layout
activeLayout = descendantTreeLayout;
// use curved edges optimized for the direction chosen on
// the directionSelect pull down menu.
display.template('edge').as(
thinkmap.display.edgestyle.curved().axis(axis)
);
fixRotations();
// Cause the display to layout.
display.layout();
}
}
This function adjusts the text rotation to correspond to the pull down menus.
// Rotate the text and the rectangles based on the values of the pulldown
// menus.
function fixRotations(){
if (descendantRadialLayout.enabled()) {
//if we are in radial mode, keep the text right side up
flipText();
} else {
// the current value of the direction pull down menu ('x' or 'y')
var axis = document.getElementById('directionSelect').value;
if (axis=='y') {
// Rotate all the rotatable ('text' and 'rect') elements of
// all descendants 45 degrees.
display.select(descendantTree).elements()
.selectAll('.rotatable').attr('transform','rotate(45)');
// Remove the rotation of all rotatable elements from ancestors.
display.select(ancestorTree).elements()
.selectAll('.rotatable').attr('transform','');
} else {
// Remove the rotation of all rotatable elements from employees.
display.select('employee').elements().selectAll('.rotatable')
.attr('transform','');
}
}
}
Because the radial layout rotates the entire entity, it will sometimes cause the text from an entity to be upside down. This function takes text in the radial layout that is upside down, and flips it.
// this function is used in radial mode to ensure that text stays
// right-side-up.
function flipText() {
// Create an element selection of all the 'text' elements associated with an employee
display.select('employee').elements().selectAll('text')
// Apply a transform to the elements.
.attr('transform',function(entity) {
// get the target rotation of the node (where it is animating to)
var angle = ancestorTree.contains(entity) ? ancestorRadialLayout.targetRotation(entity) :
descendantRadialLayout.targetRotation(entity);
// flip the text if the angle is more than 90 degrees (in either direction)
if (Math.abs(angle) > 90 ) {
// rotate 180 degrees around the center of the text
var bBox = this.getBBox();
var cx = bBox.x + bBox.width/2;
var cy = bBox.y + bBox.height/2;
return 'translate(' +cx+ ',' +cy+') rotate(180) translate('+(-cx)+','+(-cy)+')';
} else {
return '';
}
});
}
In Conclusion
This tutorial is a good introduction as to how you can use the radial layout or the tree layout to show hierarchical information. As you continue to work with Thinkmap, you'll see that there are many different ways for presenting this type of information.