Create dynamic graphs and charts using Dojo

Data visualization with the dojox.charting module

In the world of Web 2.0, web pages are becoming more like applications, and web development libraries (such as Dojo and jQuery) are playing an increasingly important role. In this article, learn to use the dojox.charting feature of the Dojo library for data visualization. You can quickly and easily add great-looking and functional dynamic charts and graphs to your web pages. All you need are some basic JavaScript skills and a copy of Dojo.

Share:

Xiang Zhou, Software Engineer, IBM

Zhou Xiang photoZhou Xiang は上海にある IBM China Development Lab の Federated Integration Test チームのソフトウェア技術者です。彼はこれまで Lotus Mashups と UT/ClickTrack の業務に従事していました。現在は、dijit Claro テーマの開発、dojox グラフ機能の新機能など、Dojo ライブラリーの開発を行っています。彼の連絡先は xiangxz@cn.ibm.com です。



02 November 2010

Also available in Chinese Japanese

Introduction

Develop skills on this topic

This content is part of a progressive knowledge path for advancing your skills. See Get started with Dojo development

Web development libraries, such as Dojo and jQuery, are becoming more important as Web 2.0 gains popularity. Web pages are increasingly becoming more like applications. With Dojo's charting module, you can quickly and easily add great-looking and functional dynamic charts and graphs to your web pages.

In this article, learn to use the many features of the dojox.charting module. Examples and code samples walk you through the charting features in the new Dojo Toolkit 1.5.


Overview of charts

This section provides an overview of the major chart types available in the Dojo visualization library.

Line charts

With a basic line chart you can draw lines and place markers at data points. There are several types of line charts:

  • Default: Universal line chart capable of drawing lines, filling areas under them, and placing markers at data points; this plot type is used if no plot type was specified when adding it to a chart.
  • Lines: Basic line chart; uses Default
  • Areas: Area under data lines are filled; uses Default
  • Markers: Lines with markers; uses Default
  • MarkersOnly: Markers, sans lines; uses Default

Figure 1 shows an example of a line chart with markers.

Figure 1. Line chart with markers
A line chart showing markers, lines, 2D data, a custom axis, and a blue theme

Stacked line charts

Options for stacked line charts include:

  • Stacked: Data sets charted in relation to the previous data set; extension of Default
  • StackedLines: Stacked data sets using lines; uses Stacked
  • StackedAreas: Stacked data sets with filled areas under chart lines; uses Stacked

For example, Figure 2 shows a stacked areas chart having stacked data sets with filled areas under chart lines.

Figure 2. Stacked area chart
A stacked area charting showing stacked areas, axes (aligned on major ticks), and custom strokes and fills

Bars

For classic bar charts you have:

  • Bars: Horizontal bars
  • ClusteredBars: Horizontal bars with clustered data sets; uses Bars
  • StackedBars: Stacked data sets with horizontal bars; uses Bars

Columns

The various types of column charts are:

  • Columns: Vertical bars
  • ClusteredColumns: Vertical bars with clustered data sets; uses Columns
  • StackedColumns: Stacked data sets with vertical bars; uses Columns

For example, clustered columns have vertical bars with clustered data sets, as shown in Figure 3. This is a more complex version of a column chart.

Figure 3. Clustered column chart
A clustered column chart showing clustered columns with positive and negative values, axes, and grid

Stacked columns are another complex version of a column chart. They show stacked data sets with vertical bars, as shown below.

Figure 4. Stacked column chart
A stacked column chart showing stacked columns differentiated by color

Miscellaneous

The following charts are in the miscellaneous category:

  • Pie: Probably one of the most common types of charts
  • Scatter: Similar to MarkersOnly, yet you can chart using gradient fields
  • Grid: For adding a grid layer to your chart

The pie chart, a circular chart divided into sectors, illustrates proportion.

Figure 5. Pie chart
A pie chart showing internal custom labels, custom colors, and custom tooltips

Map chart

In a map chart you can draw a map based on geography data. Learn more about the map chart near the end of this article.

Figure 6. Map chart
A map chart of the United States showing series, data, and a legend

Using Dojo charting

This section outlines some of the features of Dojo charting.

Listing 1 shows the basics for creating a chart using the Dojo visualization library. There are four methods: addAxis, addPlot, addSeries, and render.

Listing 1. The basics for creating a chart using the Dojo visualization library
<div id="test1" style="width: 200px; height: 200px;"></div>
                
makeObjects = function(){
var chart1 = new dojox.charting.Chart2D("test1");
chart1.addAxis("x", {fixLower: "major", fixUpper: "major", includeZero: true});
chart1.addAxis("y", {vertical: true, fixLower: "major", fixUpper: "major",
 natural: true});
chart1.addPlot("default", {type: "Bars"});
chart1.addSeries("Series A", [1, 2, 3, 4, 5], {stroke: {color: "red"}, 
fill: "lightpink"});
chart1.addSeries("Series B", [5, 4, 3, 2, 1], {stroke: {color: "blue"}, 
fill: "lightblue"});
chart1.render();
};
dojo.addOnLoad(makeObjects);

To configure any chart you need to define three necessary parts:

Plots
Describe how data is to be visualized; for example, a column, bar, or pie
Axes
Describe the dimensions of data that are being visualized; this is the X axis or Y axis definition and includes things such as specifying label text and label rotation
Series data
Describes the data that the chart will visualize

Plot configuration

The addPlot() function accepts two parameters: a name and an arguments array. The name is the identifier when you want to have more than one plot type on your chart. The arguments array contains your plot options, which depend on the type of plot you use.

addPlot("default", {type: "Areas", tension:"X"})

Specifying axes

Use the addAxis() method to specify a chart axis. The addAxis() call on a chart has several options for defining axes. Similar to addPlot(), this call takes two parameters: a name and an options array. You will need to use default values x and y as your axes names unless you gave them custom names in your addPlot() call.

You do not have to define the axes if you want to create charts with one or zero axes. You can also make charts with more than two axes by adding a second plot and attaching axes to it. Using this approach, you can display up to four different axes (two vertical and two horizontal) by setting a leftBottom parameter in addAxis() using two to four plots.

A single axis can also be shared by more than one plot. You could have two plots that use the same horizontal axis but have different vertical axes. Listing 2 shows all the addPlot() options that make this, and more, possible.

Listing 2. addPlot() options
chart.addAxis("x2", {fixLower: "minor", natural: true, leftBottom: false, 
    stroke: "grey", majorTick: {stroke: "black", length: 4}, majorLabels: true});
chart.addAxis("y2", {vertical: true, min: 0, max: 20, leftBottom: false, 
    stroke: "grey", majorTick: {stroke: "black", length: 4}, 
    minorTick: {stroke: "gray", length: 2}});
chart.addPlot("plot2", {type: "Areas", hAxis: "x2", vAxis: "y2", 
    animate: {duration: 1800}});

Enabling and disabling tick marks

You can turn tick marks on and off at the minor and micro level. You can also turn labels on and off for the major and minor levels. For example, if majorTick is not false, your chart will show the tick marks along the axis.

The label parameter is similar to the tick parameters. If majorLabels equals false, your chart will not show the labels for corresponding ticks even if you already set the label text. See Listing 2 above.

Using custom axis labels

Dojo charts provide the ability to assign custom labels to any axis. Be sure to allow sufficient space in your div for the text to display properly. Listing 3 shows how to use abbreviated month names with a Columns plot.

Listing 3. Use abbreviated month names with a Columns plot
chart4.addAxis("y", {
		vertical: true, 
		fixLower: "none", 
		fixUpper: "none", 
		natural: true,
		majorTick: { length: 3 },
		labels: [
			{value: 0, text: ""},
			{value: 1, text: "January"}, 
			{value: 2, text: "February"},
			{value: 3, text: "March"}, 
			{value: 4, text: "April"},
			{value: 5, text: "May"} 
		]
	});

Series configuration

Using addSeries() you can define the data sets that will be displayed on the chart. addSeries() accepts three parameters: a name, a data array, and an options array. There is also an updateSeries() call that takes a name and data array for when you want to refresh your data.

The options for the addSeries() call are:

  • stroke covers the color and width of your line or the border of your bar and column graphs.
  • fill determines the color of the fill area under the line in area line graphs and determines the bar fill color for bar and column graphs.

If you're familiar with SVG or dojox.gfx, you'll recognize stroke and fill.

addSeries("Series A", [1, 2, 3, 4, 5], {stroke: {color: "red"}, 
 fill: "lightpink"})

The data array sometimes is just an array of data. All plot types can accept a one-dimensional array, but there are some additional format options available based on the type of chart. With a one-dimensional array for line type graphs, the X axis will be integers (1,2,3...), and the data will be the Y axis. For bar type plots, the data is the length of the bar, and the choice between column or bar type determines the orientation. For pie charts, the sum of the array is your whole pie. All the plot types except pie can have multiple series.

Listing 4. addSeries() in action
addSeries("Series A", [
	{ x: 0.5, y: 5 },
	{ x: 1.5, y: 1.5 },
	{ x: 2, y: 9 },
	{ x: 5, y: 0.3 }
]).
addSeries("Series B", [
	{ x: 0.3, y: 8 },
	{ x: 4, y: 6 },
	{ x: 5.5, y: 2 }
])

For pie charts you can specify additional information, such as: the text label for each slice, the color of the slice, and a font color that overrides the font color definable in the addPlot() call. Listing 5 shows an example.

Listing 5. addSeries() for a pie chart
chart6.addSeries("Series A", [
		{y: 4, text: "Red", color: "red"},
		{y: 2, text: "Green", color: "green"},
		{y: 1, text: "Blue", color: "blue"},
		{y: 1, text: "Other", color: "white", fontColor: "black"}
	]);

Chart events

Dojo charting has its own way to attach an event. connectToPlot is a very useful method for event handling. Chart events allow you to attach behavior to various chart features, such as markers, in response to user actions. The following events are supported:

  • onclick
  • onmouseover
  • onmouseout

Event handlers can be attached to individual plots of a chart, as shown in Listing 6.

Listing 6. Event handlers can be attached to individual plots of a chart
      chart1.connectToPlot("default", function(args){
		switch(args.type){
			case "onclick":
				if(args.index == 1){
					var shape = args.shape;
					//TODO...
				}
				break;
			case "onmouseover":
				//TODO...
				break;
			case "onmouseout":
				//TODO...
				break;
			default:
				//TODO...
				break;
		}
	});

Zooming

Dojo charting provides methods to control zooming to drill down to the smallest details of your chart, including scrolling and panning (moving the chart with your mouse in two dimensions). Beware that panning can be taxing on the browser, but the new generation of browsers (Firefox 3, Safari 3, Opera 9.5) are up to the task. Dojo charting also now has animation effects for zoom in and out that will improve the user experience.

chart.zoomIn("x", [50, 80]);  
//zoom into [50, 80] which is part of total zone [0, 100] on x axis

Actions and animated effects

Actions are self-contained objects that use events to implement certain effects when users interact with a chart. In general, they're designed to either attract attention and indicate which charting element is selected, or to show additional information.

The default library contains the following five actions: Highlight, Magnify, MoveSlice, Shake, and Tooltip. All of them take advantage of the Dojo animation support.

Highlight
Highlights (changes a color by modifying a fill) individual elements of a chart when a user hovers over an element with the mouse; affected elements include: markers, columns, bars, circles, and pie slices.
var anim1c = new dc.action2d.Highlight(chart1, "default", {
		duration: 2000,
		easing: dojo.fx.easing.sineOut,
		highlight: "blue"
	});
Magnify
Magnifies an individual element of a chart when a user hovers over it with the mouse; this effect is always used together with the highlight effect. Affected elements include markers and circles.
var anim9a = new dc.action2d.Magnify(chart1, "default", {
scale: 1.5
        });
MoveSlice
Moves slices out from a pie chart; it actually takes some offset on slice's x and y position when a user hovers over an element with the mouse.
 var anim10a = new dc.action2d.MoveSlice(chart10, "default", {
		    scale: 2,
		    shift: 5
		});
Shake
Shakes charting elements when a user hovers over an element with the mouse; affected elements include: markers, columns, bars, circles, and pie slices.
var anim6b = new dc.action2d.Shake(chart6, "default"{
		    shiftX: 5,
		    shiftY: 10
		});
Tooltip
Shows a tooltip, but it is actually a dijit.Tooltip with some position customization; it always anchors at the middle when users hover over a charting element with the mouse. Affected elements include: markers, columns, bars, circles, and pie slices.
var anim1b = new dc.action2d.Tooltip(chart1, "default", {text: function(args){
return args.index < 2 ? "good" : "bad";
 }});

The tooltip content can be customized for different functions.

The chart widget

One of the easiest ways to use Dojo charting is to use the Chart2D widget. It provides a way to use the dojo charting widget the same way you'd use the dojo standard widget. Embed it into HTML source using dojoType = ‘dojox.charting.widget.chart2D’ instead of creating a dojo chart widget programmatically. Listing 7 is taken from a Dojo Chart2D widget test.

Listing 7. A Dojo Chart2D widget test
<div dojoType="dojox.charting.widget.Chart2D" id="chart1" 
    style="width: 300px; height: 300px;">
        <div class="axis" name="x" font="italic normal normal 8pt Tahoma"></div>
        <div class="axis" name="y" vertical="true" fixUpper="major" includeZero="true" 
        font="italic normal normal 8pt Tahoma"></div>
        <div class="plot" name="default" type="Areas"></div>
        <div class="plot" name="grid" type="Grid"></div>
        <div class="series" name="Run A" data="1, 2, 0.5, 1.5, 1, 2.8, 0.4"></div>
        <div class="series" name="Run B" array="seriesB"
        legend="&lt;em&gt;Custom&lt;/em&gt; legend"></div>
        <div class="series" name="Run C" store="tableStore" valueFn="Number(x)"></div>
</div>

Chart legend widget

The chart legend widget is an independent widget for Dojo chart's legend rendering. You can add a legend widget to your charts using dojox.charting.widget.Legend. The legend automatically takes on the shape markers and colors of the chart to which it is attached. By default, the legend widget uses the legend parameter of a series. It reverts to the name parameter if legend is not specified.

For a pie chart, the behavior of a legend is different. If the chart was specified with an array of numbers, it will use numbers. Otherwise, it will check object properties in the following order: legend, text, and the numeric value.

var legend1 = new dc.widget.Legend({chart: chart1, horizontal: true}, "legend1");

Dojo Toolkit 1.5 features

This section outlines some of the new features related to charting in the Dojo Toolkit 1.5.

Map chart

The Map widget, dojox.geo.charting.Map, is a fantastic new widget that lets you easily create a map on a web page. The map chart supports data that holds detailed information for each map feature. Each map can be divided into several features; for example, a feature could be a country based on a world map, or a province based on a country map. You can also customize the tooltip data for each map feature. For each feature, the zoom in/out effect and customized interactive event are provided.

Listing 8 shows a test case for the map chart widget.

Listing 8. Test case for the map chart widget
dojo.require("dojox.geo.charting.Map");
dojo.addOnLoad(function(){
	var USStates = new dojox.geo.charting.Map("USStates",
"../resources/data/USStates.json");
	USStates.setMarkerData("../resources/markers/USStates.json");
});

In the example above, USStates.json is the map chart data source. Listing 9 shows the content, including comments describing the detailed data.

Listing 9. Map chart code including comments

Click to see code listing

Listing 9. Map chart code including comments

new dojox.geo.charting.Map(container, shapefile)// container//	map container html node/id// shapefile//	map shape data url, handle as json

shapefile data format:

{
  //layerExtent: map boundary
  "layerExtent":[0, 0, 8036, 5263],
  //"featureNames: list of map unit, like a province in a country map
"featureNames":["RI", "VT", "HI", "ME", "VA", "MI", "DE", "ID", "IA", "MD", "MA",
"AR", "IL", "UT", "IN", "MN", "AZ", "MO", "MT", "MS", "NH", "NJ", "NM", "AK", "TX",
"AL", "NC", "ND", "NE", "NY", "GA", "NV", "TN", "CA", "OK", "OH", "WY", "FL", "SD",
"SC", "CT", "WV", "DC", "WI", "KY", "KS", "OR", "LA", "WA", "CO", "PA"],
  //features: map unit shape info
  "features":{
    "RI":{
      //unit shape vertex described in polygon: [[polygon1_vertex1_x,
polygon1_vertex1_y, p_v2_x, p_v2_y, ...], [p2_v1_x, p2_v1_y, ...], ....]
      "shape":[[7641, 1436, 7651, 1437, 7661, 1467, 7661, 1467, 7653, 1478, 7641,
1436], [7541, 1398, 7559, 1392, 7598, 1380, 7615, 1420, 7635, 1430, 7635, 1431, 7627,
1445, 7626, 1427, 7615, 1429, 7607, 1410, 7618, 1435, 7606, 1444, 7617, 1460, 7618,
1506, 7612, 1496, 7568, 1527, 7568, 1526, 7541, 1398], [7633, 1474, 7639, 1442, 7645,
1476, 7631, 1485, 7633, 1474]],
      //center: center point
      "center":[7585, 1442],
      //shape's rectangle boundary
      "bbox":[7541, 1380, 120, 147]
    },
    "VT":{
      "shape":[7427, 828, 7434, 848, 7424, 882, 7445, 909, 7444, 926, 7390, 984, 7404,
1022, 7383, 1128, 7402, 1236, 7394, 1266, 7414, 1289, 7393, 1294, 7309, 1313, 7302,
1314, 7267, 1166, 7255, 1151, 7239, 1162, 7241, 1126, 7216, 1076, 7218, 999, 7196,
969, 7184, 893, 7202, 888, 7427, 828],
      "center":[7317, 1057],
      "bbox":[7184, 828, 261, 487]
    },
    .......
  }
}

The map chart that would display on a web page is shown in Figure 7.

Figure 7. Simple map chart
Map chart of the United States showing Kansas. The chart shows how this simple map supports zoom in and zoom out.

Gradient and pattern

The new Dojox charting gradient feature provides a nice gradient fill effect on your chart. The gradient feature can be customized in a chart theme. The gradient feature is based both on plot and shape. It also provides linear and radial gradient styles.

Figure 8 shows different gradient effects.

Figure 8a. Linear and radial gradients
A column chart showing a linear gradient of red and blue
Figure 8b. Linear and radial gradients (continued)
Another column chart showing a linear gradient of red and yellow
Figure 8c. Linear and radial gradients (continued)
A chart showing a radial gradient of yellow and red

The first chart in Figure 8 is gradient on each shape. The middle chart is gradient on plot. Both of them are linear gradients. The last chart in Figure 8 is a radial gradient. Listing 10 shows the code for this example.

Listing 10. Code for gradient effects
var theme1 = new dojox.charting.Theme({
        seriesThemes: [
            {
                fill: {
                    type: "linear", space: "plot", x1: 0, y1: 0, x2: 100, y2: 100,
                    colors: [{ offset: 0, color: "white" }, { offset: 1, color: "red" }]
                }
            },
            {
                fill: {
                    type: "linear", space: "plot", x1: 0, y1: 100, x2: 100, y2: 0,
                    colors: [{ offset: 0, color: "white" }, { offset: 1, color: "blue" }]
                }
            },
            {
                fill: {
                    type: "linear", space: "plot", x1: 0, y1: 0, x2: 100, y2: 100,
                    colors: [{ offset: 0, color: "white" }, { offset: 1, color: "green" }]
                }
            }
        ]
    });

var chart1 = new dojox.charting.Chart2D("c1").
    setTheme(theme1).
    addAxis("x", {fixLower: "major", fixUpper: "major", natural: true}).
	addAxis("y", {vertical: true, fixLower: "major", fixUpper: "major", 
	includeZero: true,  minorTickStep: 0.5}).
    addPlot("default", {type: "Columns"}).
    addSeries("Series A", [1, 2, 3, 4, 5]).
    addSeries("Series B", [5, 4, 3, 2, 1]).
	render();

You can see that the gradients are all customized in theme1. The fill parameter type can be linear or radial, space can be plot or shape, and so on. Listing 11 shows details.

Listing 11. The gradient effect using the fill parameter

Click to see code listing

Listing 11. The gradient effect using the fill parameter

seriesThemes: [
    {
        fill: {
	// summary: fill for plot1// type: string://	gradient fill type  e.g. “linear”, “radial”// space: string://	gradient fill area  e.g. “plot”, “shape”, “shapeX”// x1: Number: //	gradient fill start point offset percentage(0-100) for x Axes// x2: Number: //	gradient fill end point offset percentage(0-100) for x Axes// y1: Number: //	gradient fill start point offset percentage(0-100) for y Axes// y2: Number: //	gradient fill end point offset percentage(0-100) for y Axes// colors: Array//	gradient fill settings
            type: "linear", space: "plot", x1: 0, y1: 0, x2: 100, y2: 100,
            colors: [{ offset: 0, color: "white" }, { offset: 1, color: "red" }]
        }
    },
    {
        fill: {
            type: "linear", space: "plot", x1: 0, y1: 100, x2: 100, y2: 0,
            colors: [{ offset: 0, color: "white" }, { offset: 1, color: "blue" }]
        }
    },
    {
        fill: {
            type: "linear", space: "plot", x1: 0, y1: 0, x2: 100, y2: 100,
            colors: [{ offset: 0, color: "white" }, { offset: 1, color: "green" }]
        }
    }
]

You customize patterns the same way you customize gradient.

Using the API provided for gradient, you can customize many complex gradient effects that look great. Figure 9 shows a complex gradient effect on a bar chart.

Figure 9. Gradient with bar chart
Bar chart showing a complex gradient of red, yellow, and blue

Summary

This article provided an overview of all the major chart types in the Dojo visualization library. You learned basic usage for popular charts, including plot, axis, and series. The article explored zooming, actions, and animated effects. You also learned about some of the new Dojo 1.5 mapping and charting features.

Resources

Learn

Get products and technologies

Discuss

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into Web development on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Web development
ArticleID=563072
ArticleTitle=Create dynamic graphs and charts using Dojo
publish-date=11022010