Search code examples
matlabmatlab-figure

How to change the color of lines as part of a plot based on a separate vector of values?


I have a collection of values stored in a 350x130 matrix, r, that I'm using to create a simple plot in Matlab:

figure;
plot(r)

Is there a way to color the resulting lines from r using another 350x1 vector, v? V contains a collection of integers, in this case, that vary from 1 to 4.

I'm imaging the call would look something like this, where, again, r is 350x130 and v is 350x1:

figure;
plot(r,v)

Solution

  • Let's define some example data:

    r = rand(10,15);
    v = randi(4,1,15);
    

    Method 1 (more fun): using a comma-separated list

    This creates a cell array and transforms it into a comma-separated list to call plot as plot(x1, y1, s1, x2, y2, s2, ...). The colors are limited to be defined as plot's linespec strings (such as 'g' or 'c+').

    linespecs = {'r' 'g' 'b' 'm'};
    c = repmat({1:size(r,1)}, 1, size(r,2));
    c(2,:) = num2cell(r, 1);
    c(3,:) = linespecs(v);
    plot(c{:})
    

    Method 2 (more readable and flexible): using a loop

    linespecs = {'r' 'g' 'b' 'm'};
    hold on
    for k = 1:size(r,2)
        plot(r(:,k), linespecs{v(k)})
    end
    

    This method allows using a colormap to specify arbitrary colors, not limited to linespec strings:

    colors = winter(4); % arbitrary colormap
    hold on
    for k = 1:size(r,2)
        plot(r(:,k), 'color', colors(v(k),:))
    end