Plotting a density map

28.11.2011 20:04

Density maps are one of those things I need rarely enough that I forget how I did it last time but also often enough that spending 15 minutes searching on Google and browsing Octave manual seems unnecessary.

So, for my reference and yours, here's the simplest, fastest way I know of producing one on a vanilla GNU/Linux box. Density plot is something Gnuplot doesn't know how to do by itself. So you need to fire up Octave:

octave> [c,x,y] = hist2d(load("foo"), 150, 150); imagesc(x,y,c)

Here, foo is a tab-separated-values text file with two columns: X and Y coordinate of each point. The two numerical arguments to hist2d are the numbers of buckets for each axis. This produces a plot like this by default:

Example density map

As with all Octave plots, you can write the current picture to a file using:

octave> print -dpng foo.png

On Debian you need octave-plot package installed for hist2d to work. See Octave manual for ways to further customize the look.

By the way, you might have noticed that the Y axis is up-side-down on the example plot above. That seems to be a bug in Octave when you only have negative values on the axis and I haven't yet figured out how to work around it.

Update: Running set(gca,'ydir','normal'); after the imagesc command restores the usual orientation of the axes for image plots.

Posted by Tomaž | Categories: Code

Add a new comment


(No HTML tags allowed. Separate paragraphs with a blank line.)