Draw simple graphs

Hi,

I am writing sample programs for graph problems like Dijkstra or Bellman-Ford algorithms. In Dijkstra, for instance, when I input my program a set of vertices and edges, ask to find shortest path from Vertex A to Vertex B, my program currently outputs shortest path from A to B. I want to display graph and have a visualization of the output generated. Is there a way to display nodes and connecting lines? What C++ classes would help achieve this?

Thanks!
Check out qwt. It' a tool-set meant to compliment Qt.

Qt is a nice GUI creator. You can re-implement the paint function in QWidget to draw a widget in whatever way you like. qwt project will provide many different classes which inherit from QWidget. These are aimed at technical data representation such as graphing.

Here's the doxygen documentation of the project:
http://qwt.sourceforge.net/
Last edited on
For what you want to do, it would be a complete overkill to try to learn to do it in C++. You can do it, and it isn't really difficult, but where you are there is a fairly steep learning curve before you can do very much useful.

I actually recommend you use Tcl/Tk instead. The Tk::canvas is exceedingly powerful and using it to draw stuff is astonishingly simple.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
proc graph {canvas coords n xtext ytext points} {

  lassign $coords lt tp rt bt 

  incr lt  20
  incr rt -$n
  incr tp  $n
  incr bt -20

  # Draw the labels
  $canvas create text [expr {$lt+(($rt-$lt)/2)}] [expr {$bt+10}] -text $xtext
  $canvas create text [expr {$lt-10}] [expr {$tp+(($bt-$tp)/2)}] -text [join [split $ytext {}] \n]

  # Draw the axes
  $canvas create line $lt $tp $lt $bt -arrow first
  $canvas create line $lt $bt $rt $bt -arrow last
  
  # transform the list of points to our canvas's coordinate system
  foreach point $points {
    lassign $point x y
    lappend points2 [expr {$lt + (($rt - $lt) * $x)}]
    lappend points2 [expr {$bt - (($bt - $tp) * $y)}]
  }
  
  # draw the lines of the graph between points
  $canvas create line {*}$points2 -fill red
  
  # draw a dot at each point
  foreach {x y} $points2 {
    $canvas create oval [expr {$x-$n}] [expr {$y-$n}] [expr {$x+$n}] [expr {$y+$n}] -fill red -outline red
  }
  
}

# create and display our canvas
canvas .c -width 420 -height 300
pack .c

# draw our graph on it
graph .c {0 0 420 300} 3 Time Productivity {
  {0.0  0.00} 
  {0.1  0.20} 
  {0.2  0.07} 
  {0.3  0.50}
  {0.4  0.50}
  {0.5  0.69}
  {0.6  0.71}
  {0.7  1.00}
  {0.8  0.33}
  {0.9  0.46}
  {1.0  0.67}
}

I hacked this up for you. Notice that the only caveat is that all the points in the graph must be scaled between 0 and 1.

Have fun!
Topic archived. No new replies allowed.