Click here to Skip to main content
Licence 
First Posted 26 Jun 2002
Views 61,912
Bookmarked 25 times

Creating graphs using JavaScript

By | 26 Jun 2002 | Article
JavaScript can be used to dynamically generate a bar graph with user supplied data. This article shows you how.

Introduction

JavaScript can be used to dynamically generate a bar graph with user supplied data. This is due to the simplicity of bar graphs in general, which consists simply of images of varying lengths. We use JavaScript to dynamically write out each image, each with its length calculated using the data entered.

All we need is a simple 1x15 image to start things off:

 

If I wanted to stretch this image to 50x15, I do so by generating the image using JavaScript:

<script>
document.write(<img src="poll.gif" width="50" height="15">')
</script>
 

And with this forms the basis of a dynamic bar graph! Here's a simple script I wrote that demonstrates a working example of graph creation using JavaScript:

<script>
var graphtext=new Array("Jill", "Bob", "Tony") //Graph items
var graphvalue=new Array("60", "45", "95") //Graph values (in percentage, so 70=70%)
var barlength=200
for (i=0;i<graphtext.length;i++)
document.write (graphtext[i]+
        ': <img src="poll.gif" width="'+
        graphvalue[i]/100*barlength+
        '" height="15"><br>')
</script>
Jill: 
 
Bob:
 
Tony  
 

The secret here is the code:

width="'+graphvalue[i]/100*barlength+'"

This makes the width of the graph dynamic and based on the data supplied by the user. Basically each width is derived by dividing the input value by 100 to get its percentage equivalent, then multiplied by the baseline bar image length.

There you have it! Dynamic graphs made possible using JavaScript. You may want to take a look at a script called JavaScript Graph-It from JavaScript Kit, which is a user friendly and more sophisticated JS graphing script. That's where I got the general idea of this tutorial from.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Andy-Scott



United States United States

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Mobile
Web03 | 2.5.120517.1 | Last Updated 27 Jun 2002
Article Copyright 2002 by Andy-Scott
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid