5

I would like to plot a simple scatter graph in MATLAB, with marker colours varying from one end of the spectrum to the other (e.g. red, orange, yellow....blue, purple).

My data compares the amount of water in a river with the quality of the water, over time (3 simple columns: time, amount, quality). I would like to plot the x,y scatter plot of amount vs quality, but with the colour progressing over time, so that it is possible to see the progression of the quality over time.

I will need to produce many graphs of this type, so if I can find a piece of code that will work for any length of dataset, that would be really useful.

Many thanks in advance for helping a Matlab novice!

Shai
  • 111,146
  • 38
  • 238
  • 371
user1913275
  • 73
  • 1
  • 1
  • 6

2 Answers2

10

You can use the color argument of scatter

If your data are already sorted in time than simply use:

% let n be the number of points you have
cmp = jet(n); % create the color maps changed as in jet color map
scatter(x, y, 10, cmp, 'filled');

Otherwise you need to sort your data first:

[time, idx] = sort(time);
x = x(idx);
y = y(idx);
cmp = jet(n); % create the color maps changed as in jet color map
scatter(x, y, 10, cmp, 'filled');
slayton
  • 20,123
  • 10
  • 60
  • 89
Shai
  • 111,146
  • 38
  • 238
  • 371
  • 1
    Brilliant! Thank you so much for your help, this is much simpler than some other codes to do similar things which I was trying to understand, and exactly what I needed. – user1913275 Dec 18 '12 at 15:22
2

The simplest way to color a scatter plot by an additional variable is to simply pass it as the "color"-argument. Say you have x, y, and time (where time is a numeric vector. If time contains date strings instead, call datenum on it, first). Then you can write

scatter(x,y,[],time,'filled')

The colorbar axes will then show you which point in time a specific color corresponds to. Importantly, this will properly advance colors even in case the time between measurements isn't uniform.

/aside: The default colormap is jet, which is pretty bad for visualizing smooth transitions, I suggest you download a perceptually improved colormap from the File Exchange. To use it to set the colormap, you can then call

cmap = pmkmp(length(time));
colormap(cmap);
Jonas
  • 74,690
  • 10
  • 137
  • 177