Hate UML?

Draw sequence diagrams in seconds.

Drawing Graphs with Physics
Posted on: 2009-05-08 21:42:40

I use graphviz whenever I need to draw state machine diagrams. Drawing circles connected with lines is a hard problem for computers, because they have to decide where to place the circles so the diagram makes sense. These types of diagrams are called graphs.

To my surprise, I found that there is a very simple way to arrange graphs that can be expressed in only a few lines of code, using force-directed placement [Fruchterman, 1991]. We pretend that the nodes on the graph all strongly repel each other. However, on the other hand, nodes that are connected attract each other with a weaker force. It is as if you had a bunch of statically charged styrofoam balls connected with springs, and its very fun to watch.

Click the image to reset it.

Here's the code that moves the nodes around.

Springs.prototype.recalc = function()
    var width = this.ctx.canvas.width;
    var height = this.ctx.canvas.height;

    // K is related to how long the edges should be.
    var k = 200.0;

    // C limits the speed of the movement. Things become slower over time.
    var C = Math.log( this.frame + 1 ) * 100;

    // calculate repulsive forces
    for ( var vindex = 0; vindex < this.graph.nodes.length; vindex++ ) 
        var v = this.graph.nodes[vindex];

        // Initialize velocity to none.
        v.vx = 0.0;
        v.vy = 0.0;

        // for each other node, calculate the repulsive force and adjust the velocity
        // in the direction of repulsion.
        for ( var uindex = 0; uindex < this.graph.nodes.length; uindex++ ) 
            if ( vindex == uindex ) {

            var u = this.graph.nodes[uindex];

            // D is short hand for the difference vector between the positions
            // of the two vertices
            var Dx = v.x - u.x;
            var Dy = v.y - u.y;
            var len = Math.pow( Dx*Dx+Dy*Dy, 0.5 ); // distance
            if ( len == 0 ) continue;
            var mul = k * k / (len*len*C);
            v.vx += Dx * mul;
            v.vy += Dy * mul;

    // calculate attractive forces
    for ( var eindex = 0; eindex < this.graph.edges.length; eindex++ ) 
        var e = this.graph.edges[eindex];

        // each edge is an ordered pair of vertices .v and .u
        var Dx = e[0].x - e[1].x;
        var Dy = e[0].y - e[1].y;
        var len = Math.pow( Dx * Dx + Dy * Dy, 0.5 ); // distance.
        if ( len == 0 ) continue;

        var mul = len * len / k / C;
        var Dxmul = Dx * mul;
        var Dymul = Dy * mul;
        // attract both nodes towards eachother.
        e[0].vx -= Dxmul;
        e[0].vy -= Dymul;
        e[1].vx += Dxmul;
        e[1].vy += Dymul;

    // Here we go through each node and actually move it in the given direction.
    for ( var vindex = 1; vindex < this.graph.nodes.length; vindex++ ) 
        var v = this.graph.nodes[vindex];
        var len = v.vx * v.vx + v.vy * v.vy;
        var max = 10;
        if (this.frame > 20) max = 2.0;
        if ( len > max*max ) 
            len = Math.pow( len, 0.5 );
            v.vx *= max / len;
            v.vy *= max / len;
        v.x += v.vx;
        v.y += v.vy;

Its really fun to play with this method. Here's what happens if we add a bit of gravity to the system. (Click to reset)

Coding that made me want to play The Incredible Machine.

Want more programming tech talk?
Add to Circles on Google Plus
Subscribe to posts

Post comment

Real Name:
Your Email (Not displayed):

Text only. No HTML. If you write "http:" your message will be ignored.
Choose an edit password if you want to be able to edit or delete your comment later.
Editing Password (Optional):

Ryan Fox

2009-05-08 23:29:42
This is the basic idea behind 'neato' and 'fdp', also included with Graphviz.

Frans Bouma

2009-05-09 04:16:33
I'm surprised you didn't know about this method, as it's one of the methods in the standard set of graph layout algorithms ;)

It's also one which can be quite problematic to get right, as it's a performance hog in dense graphs, also because it's sometimes a bit hard to get a finite state quickly (so the nodes are moved around for longer than the user might want to wait for it). Of course it's also the most coolest way to layout a graph ;) The examples look great :)

Steve Hanov

2009-05-09 12:00:52
Franz, I don't know everything yet. The last time I knew everything was on May 29, 1994 when I was 15 years old ;-)

I noticed the performance problems right away, which is why the example is small. I'm reading about some methods for improving the performance using "multipole" force calculations, which summarize the effects of distant groups of particles into a single force, and KD-Trees, which allow fast lookup to form these groups.

Matt Burns

2009-06-02 19:04:04
I've not played The Incredible Machine, but the addictive fantasticcontraption sprung to my mind ;)

Miguel Tasende

2009-06-13 12:21:42
I didn't play The Incredible Machine either. My suggestion is Armadillo Run ;).

Great webpage!

Marc Lepage

2011-03-31 19:43:55
Armadillo Run is fun.

Other posts by Steve

Yes, You Absolutely Might Possibly Need an EIN to Sell Software to the US How Asana Breaks the Rules About Per-Seat Pricing 5 Ways PowToon Made Me Want to Buy Their Software How I run my business selling software to Americans 0, 1, Many, a Zillion Give your Commodore 64 new life with an SD card reader 20 lines of code that will beat A/B testing every time [comic] Appreciation of xkcd comics vs. technical ability VP trees: A data structure for finding stuff fast Why you should go to the Business of Software Conference Next Year Four ways of handling asynchronous operations in node.js Type-checked CoffeeScript with jzbuild Zero load time file formats Finding the top K items in a list efficiently An instant rhyming dictionary for any web site Succinct Data Structures: Cramming 80,000 words into a Javascript file. Throw away the keys: Easy, Minimal Perfect Hashing Why don't web browsers do this? Fun with Colour Difference Compressing dictionaries with a DAWG Fast and Easy Levenshtein distance using a Trie The Curious Complexity of Being Turned On Cross-domain communication the HTML5 way Five essential steps to prepare for your next programming interview Minimal usable Ubuntu with one command Finding awesome developers in programming interviews Compress your JSON with automatic type extraction JZBUILD - An Easy Javascript Build System Pssst! Want to stream your videos to your iPod? "This is stupid. Your program doesn't work," my wife told me The simple and obvious way to walk through a graph Asking users for steps to reproduce bugs, and other dumb ideas Creating portable binaries on Linux Bending over: How to sell your software to large companies Regular Expression Matching can be Ugly and Slow C++: A language for next generation web apps qb.js: An implementation of QBASIC in Javascript Zwibbler: A simple drawing program using Javascript and Canvas You don't need a project/solution to use the VC++ debugger Boring Date (comic) barcamp (comic) How IE <canvas> tag emulation works I didn't know you could mix and match (comic) Sign here (comic) It's a dirty job... (comic) The PenIsland Problem: Text-to-speech for domain names Pitching to VCs #2 (comic) Building a better rhyming dictionary Does Android team with eccentric geeks? (comic) Comment spam defeated at last Pitching to VCs (comic) How QBASIC almost got me killed Blame the extensions (comic) How to run a linux based home web server Microsoft's generosity knows no end for a year (comic) Using the Acer Aspire One as a web server When programmers design web sites (comic) Finding great ideas for your startup Game Theory, Salary Negotiation, and Programmers Coding tips they don't teach you in school When a reporter mangles your elevator pitch Test Driven Development without Tears Drawing Graphs with Physics Free up disk space in Ubuntu Keeping Abreast of Pornographic Research in Computer Science Exploiting perceptual colour difference for edge detection Experiment: Deleting a post from the Internet Is 2009 the year of Linux malware? Email Etiquette How a programmer reads your resume (comic) How wide should you make your web page? Usability Nightmare: Xfce Settings Manager cairo blur image surface Automatically remove wordiness from your writing Why Perforce is more scalable than Git Optimizing Ubuntu to run from a USB key or SD card UMA Questions Answered Make Windows XP look like Ubuntu, with Spinning Cube Effect See sound without drugs Standby Preventer Stock Picking using Python Spoke.com scam Stackoverflow.com Copy a cairo surface to the windows clipboard Simulating freehand drawing with Cairo Free, Raw Stock Data Installing Ubuntu on the Via Artigo Why are all my lines fuzzy in cairo? A simple command line calculator Tool for Creating UML Sequence Diagrams Exploring sound with Wavelets UMA and free long distance UMA's dirty secrets Installing the Latest Debian on an Ancient Laptop Dissecting Adsense HTML/ Javascript/ CSS Pretty Printer Web Comic Aggregator Experiments in making money online How much cash do celebrities make? Draw waveforms and hear them Cell Phones on Airplanes Detecting C++ memory leaks What does your phone number spell? A Rhyming Engine Rules for Effective C++ Cell Phone Secrets