next up previous contents index
Next: Triangles Up: Tutorials and Examples Previous: Tutorials and Examples   Contents   Index

Drawing a graph

Here's an example of how to draw a 2-D graph. First, get rid of the current graphics (since there may be graphics from the previous tutorial):

  draw delete all

Define a function to graph, in this case, a parabola.

  proc f {x} {
   expr $x * $x
  }

The following function draws a graph given the function name, the start and end values, and the step size.

  proc draw_graph {function start end step} {
    # do some error checking
    if {$step < 0} {set step -$step}
    if {$step == 0} {error "draw_graph: cannot have step size of zero"}
    if {$start > $end} {
        set tmp $start
        set start $end
        set end $tmp
    }
    # turn materials off
    draw materials off
    # draw the data in green
    draw color green

    # calculate and save the initial coordinates
    set y0 [$function $start]
    set x0 $start
    set miny $y0
    set maxy $y0

    # go through the coordinates $start+$step to $end, $step at a time
    for {set x1 [expr $start + $step]} {$x1 <= $end} {
                                         set x1 [expr $x1 + $step]} {
        # calculate the function value for this point
        set y1 [$function $x1]
        # and draw a line to connect the previous point to the current one
        draw line "$x0 $y0 0" "$x1 $y1 0"
        # save the min/max values of y, and copy the x1,y1 into x0,y0
        if {$y1 < $miny} {set miny $y1}
        if {$y1 > $maxy} {set maxy $y1}
        set y0 $y1
        set x0 $x1
     }
     # draw a red box around everything
     draw color red
     draw line "$start $miny 0" "$end   $miny 0"
     draw line "$start $miny 0" "$start $maxy 0"
     draw line "$end   $maxy 0" "$end   $miny 0"
     draw line "$end   $maxy 0" "$start $maxy 0"
     # and put some labels down
     draw text "$end   $miny 0" "x ->"
     draw text "$start $maxy 0" "f(x)"
  }
Copy these two definitions into VMD's text console (this script is available from the VMD script library at http://www.ks.uiuc.edu/Research/vmd/script_library/), then enter
   draw_graph f -5 4 0.2
and reset the view. Presto, a nice little parabola.



vmd@ks.uiuc.edu