Thursday, 9 July 2009

Cycling colours effortlessly in multi-line MATLAB plots

Often, one needs to plot many lines in one figure, with each line being a different colour. While this can be done by selecting each line manually and changing its colour using the GUI, it is much faster doing this using DefaultAxesColorOrder. And easy too!

DefaultAxesColorOrder defines the order of colours used when plot is called. For example, if you want to switch from red to blue to green each time you use plot, you need to issue the command

set(0,'DefaultAxesColorOrder',[1 0 0;0 1 0;0 0 1])

But what do you do when you have more than just three or four colours? I prefer to use rand. Here's how. Let's assume you have twenty lines to draw in the same plot, each with a different colour. First we issue the order of colours to use:

set(0,'DefaultAxesColorOrder',rand(20,3))

So we have replaced our colour matrix by a matrix of size 20x3 with each row representing a colour. rand will always produce a uniformly distributed random number between 0 and 1. Now that we have defined our colour order, we just have to issue the plot command.

plot(0:1,rand(20,2),'linewidth',2)

For demonstration purposes, I've just drawn 20 lines with random starting and ending coordinates. See the result below:


No comments:

Post a Comment