Graphs are a powerful visual tool for conveying data to the reader. They are used in a wide range of applications, from scientific studies and traffic analysis of Web sites to marketing research and business papers. Until now, if you wanted to have a graph in your Web page or HTML email, you could take several routes. You could use a custom-built CGI to analyze your data and build a GIF file. Or, you could load up Excel (or a similar spreadsheet program), use the Graph Wizard, create a graph, paste it into a Photoshop document, and then export it as a GIF. Either way you go, it's not an easy process. Using the CGI you tax the server, and using Excel, you tax yourself.JavaScript is a powerful language--powerful enough for you to use a JavaScript library in place of a CGI or Excel for most of your graphing needs on the Net. Building a graph is easy too; if you're using a 4.0+ browser, you can skip ahead to the Graph Wizard to generate the graph you need, right away! You can even email that graph to a friend or coworker by choosing "Send Page" from the "File" menu. If you want more control over your graphs, keep reading this article to learn how to use the JavaScript Graph Builder library.
The JavaScript Graph Builder and the sample code provided in this document are provided for your use on an "AS IS" basis, under the JavaScript Graph Builder Terms of Use.
To use the library, you first have to include it. Start by downloading the library to your local hard drive. Right-click on graph.js and select "Save Link As...." Next, add the following line of code below the <HEAD> tag of your document:
<SCRIPT LANGUAGE="JavaScript1.2" SRC="graph.js"></SCRIPT>
You will also need a collection of images to reside in the same directory as the file in order for the graphs to display correctly. You can get these images by downloading graphimg.zip. Now that the library and images have been included, you can call Graph Builder functions from within the <BODY> of your document, and the graphs will be built as the page loads.
All the interaction with the JavaScript Graph Builder library takes place inside the body of your HTML document, which lets you place the graph anywhere you want among regular HTML content. Once you decide where in the page you want the graph to appear, add the following lines of code:
<SCRIPT LANGUAGE="JavaScript1.2"> var g = new Graph(400,300); </SCRIPT>
This calls the Graph object constructor function, which creates a new Graph object that you can use to set attributes of your graph before you build it. By calling the constructor function, you've already set two properties. The first argument specifies the width (in pixels) of the graph, and the second specifies the height. The Graph object above has a width of 400 pixels and a height of 300 pixels.
Once the Graph object has been created, you can set the style of the graph (more on that later) and add the data. The data is the actual information you wish to plot. Because of the limitations of HTML, it would be extremely difficult to graph a line graph or a pie chart. Therefore, the Graph Builder library builds only bar graphs. The data that you are entering are y-values in the order they appear in the graph (from left to right). The x-values will be assigned automatically, determined by the order the data is entered and the x-scale definition (see the Using Scales section).
In this example, I want to plot the number of hits on my Web page about fly fishing. I have collected the data from logs and I wish to graph it:
Date | Hits |
---|---|
8/9/98 | 124 |
8/10/98 | 138 |
8/11/98 | 216 |
8/12/98 | 143 |
8/13/98 | 256 |
8/14/98 | 302 |
To plot this data, I can use the addRow()
function and simply list the data:
<SCRIPT LANGUAGE="JavaScript1.2">
var g = new Graph(300,200);
g.addRow(124,138,216,143,256,302);
g.build();
</SCRIPT>
(Note that I highlighted the new code in grey.) You'll see that I snuck in the
build() function. Call this function after you have set all the attributes of the graph, and it will make the graph display. The result of this code is this:
Of course, this isn't a very satisfactory plot because it's unclear what exactly I am trying to plot. I'll have to do a little more work setting the Graph object attributes before I can call this a bona fide graph.
Start by setting the Y-axis scale. By setting the
scale attribute,
the Graph Builder library will automatically add a Y-axis scale. For
this data, a good scale would be 50:
<SCRIPT LANGUAGE="JavaScript1.2">
var g = new Graph(300,200);
g.addRow(124,138,216,143,256,302);
g.scale = 50;
g.build();
</SCRIPT>
Here's the result:
So now I've got a nifty Y-axis scale running up the left side of the graph to indicate the values of the bars. There's another way to get the exact values of the bars, though, which you may not have noticed. If you hold the mouse over the bar (on Windows/UNIX version of Navigator and Internet Explorer), a small yellow box will appear showing the exact value of the data. Try it!
My graph still isn't quite ready, because it's unclear to what the X-axis corresponds. There are three types of X-axis scales you can choose from. Because my data points are each on separate days, I am going to use the date-type X-axis scale. However, if I had data that I wanted to graph over hours or minutes, I would use the time-type X-axis scale. There is also the "other" type of X-axis scale which can be used to create a more generalized X-axis for almost any sort of data.
To set the starting date of the X-axis, use the
setDate() function.
This function takes three arguments: the month, the day, and the year.
Here's my example, continued:
<SCRIPT LANGUAGE="JavaScript1.2">
var g = new Graph(300,200);
g.addRow(124,138,216,143,256,302);
g.scale = 50;
g.setDate(8,10,1998);
g.build();
</SCRIPT>
Here's the result:
And that's it. In five lines of code, I've created the graph I need to convey my data. But there's much more we can do, so keep reading.
If, instead, my data points came every hour, I could use the
setTime() function
to set the starting time on the X-axis. This function takes three
arguments: the hour, the minute, and a boolean (true/false), which
specifies whether the time is AM or PM. True means PM; false means AM.
If I wasn't graphing times or dates, I could use the
setXScale() to
create a more generalized X-axis scale. This function takes only
one argument, which is the starting value of the X-axis (13, e.g.).
What if, however, I was graphing points every three days, or every
week, or even every 42 minutes? How would I do that? By setting the
Besides plotting data and setting scales, Microsoft Excel lets you add
labels to your axes, legends, and titles. Not to worry, the Graph Builder
library can handle that, too. To add a label to the X-axis, simply set
the
ADDITIONAL FUNCTIONALITY
<SCRIPT LANGUAGE="JavaScript1.2">
var g = new Graph(300,200);
g.addRow(124,138,216,143,256,302);
g.scale = 50;
g.setDate(8,10,1998);
g.title = "My Fly Fishing Page";
g.xLabel = "Date";
g.yLabel = "Hits";
g.build();
</SCRIPT>
Here's the result:
Legends are a bit more complicated. They are only relevant when you are
graphing more than one series at a time. That is simple to do, however,
by successive calls to the
addRow() function.
Say, in my example, that instead of just graphing hits on my Fly Fishing
page, I was also graphing hits on my Sport Fishing page, and that I
wanted to get an idea of how the growth in hits compare. I would want
to graph them side-by-side, and so I'd make two calls to the
addRow() function.
Then, I'd use the setLegend()
function and list the names of the series:
<SCRIPT LANGUAGE="JavaScript1.2"> var g = new Graph(300,200); g.addRow(124,138,216,143,256,302); g.addRow(201,234,340,210,314,320); g.scale = 50; g.setDate(8,10,1998); g.title = "My Web Pages"; g.xLabel = "Date"; g.yLabel = "Hits"; g.setLegend("Fly Fishing","Sport Fishing"); g.build(); </SCRIPT>
Here's the result:
Stacked and Relative-Area Graphs
Say that instead of a side-by-side graph, I want to stack the values
one on top of each other, so that I can see the total growth of hits
on my two Web pages, not just each one individually. I can do this by
setting the stacked
property to true. But say that I not only want to stack the values
on top of each other, but I want to see the relative contributions,
as a percentage, of the two Web pages to the total amount of hits.
I can do this by setting the
relative property to
true.
A stacked graph:
A relative-area graph:
Because there's quite a bit you can do with the Graph Builder library, I've compiled a Quick Reference sheet that you can print out. It also lists six other attributes not mentioned here that you can set to tweak its appearance.
Comments/Questions? Please send feedback to: mikebos@netscape.net
After getting the same request from many different developers, I decided to
update the Graph Builder library to include one more function,
setXScaleValues(). This
function takes any number of arguments (usually the number of x values) and
can be used to explicitly label each column. For instance, if you wanted to
graph the sales of different types of fruit in your store, it would be useful
to set the x-scale values to "Oranges", "Apples", and "Lemons". Calling
g.setXScaleValues("Oranges", "Apples", "Lemons")
(where g is your Graph
object) will accomplish this.
Michael
Bostock is a class of 2000 student at Princeton University in New
Jersey. He is a Computer Science major in the Engineering school.
When not interning with Netscape Communications Corporation, he is a
tenor saxophonist in the
thousand-member strong Princeton University Band.
ABOUT THE AUTHOR
For the latest technical information on Sun-Netscape Alliance products, go to: http://developer.iplanet.com
For more Internet development resources, try Netscape TechSearch.