Easy Graph Generating Code
By Stephen Bucaro
If you want to display a graph on your web page, you could use a graphics program to
draw the graph, but that's time consuming and the resulting graph is static, it can't
change or grow. In this article I will show you how to generate graphs using JavaScript.
The code in this example displays a chart of the page views served up by this web
site. But the code is easy to modify for the data that you need to display. First
let's view the results of the example code.
The data is coded as two JavaScript arrays. When you need to change or add to the data,
you edit these arrays. One array is named "month" and the other is named "views". You
can modify this for your own data. For example, your chart will probably not be about "views".
Maybe you are charting "dollars". Change the name of the "views" array to "dollars". Find
and replace the name "views" with "dollars" anywhere that you find it in the code.
Similarly, you may want to chart by the "week" instead of "month". Change the name of
the "month" array to "week". Find and replace the name "month" with "week" anywhere that
you find it in the code.
month = new Array();
views = new Array();
month[0] = "Feb 02";
views[0] = 11739;
month[1] = "Mar 02";
views[1] = 16106;
month[2] = "Apr 02";
views[2] = 15812;
month[3] = "May 02";
views[3] = 29051;
month[4] = "Jun 02";
views[4] = 23921;
month[5] = "Jul 02";
views[5] = 36680;
month[6] = "Aug 02";
views[6] = 45135;
month[7] = "Sep 02";
views[7] = 42486;
month[8] = "Oct 02";
views[8] = 68227;
month[9] = "Nov 02";
views[9] = 91546;
month[10] = "Dec 02";
views[10] = 128230;
month[11] = "Jan 03";
views[11] = 111233;
month[12] = "Feb 03";
views[12] = 84628;
month[13] = "Mar 03";
views[13] = 75141;
month[14] = "Apr 03";
views[14] = 121439;
You can add more data by adding more array element assignments with incremented indexes,
for example the next index would be 15.
You could place the data in a separate file from your web page. Don't put the
<script language="JavaScript"> and </script> tags in the data file.
Give the data file a name with the extension .js, then put an include statement
in the head of your web page. For example:
<script language="JavaScript src="filepath/filename.js"></script>
|