1
votes

I'm trying to use colormap to assign colors to lines on a plot. The data for each line is generated from a file, and the number of files imported/ lines plotted are variable each time. My code for this is:

d = uigetdir(pwd, 'Select a folder');
files = dir(fullfile(d, '*.txt'));
len = length(files);
for i = 1:len
    a = files(i).name;
    filename{i} = a;
    path = [d,'\',a];
    colour = round(random('unif',0,200,1,3))/255;
    data = dlmread(path);
    plot(data(:,1), data(:,2),'color',colour,'linewidth',2);
    hold on;
end
hold off;

At the moment the colors of the lines are generated randomly, but I would really like to use colormap (jet(n)) so that the lines run from red to blue and are equally spaced in the spectrum.

However, as a different number of files are being imported each time, I don't know how much n will be. I have tried working colormap into my code, but I get errors each time.

1

1 Answers

2
votes

You can specify the number of equally spaced colors you want from a colormap, so e.g. jet(20) will give you 20 equally spaced RGB colors from blue to red.

You can use this to color your individual lines like this:

x = [0:0.1:10];
linecolors = jet(5);
for i=1:5
    plot(x,x.^(i/3),'color',linecolors(i,:));
    hold on;
end

Colored lines

Applied to your specific problem, the code looks something like this (untested):

d= uigetdir(pwd, 'Select a folder');

files = dir(fullfile(d, '*.txt'));

len = length(files);

linecolors = jet(len);

for i = 1:len

    a = files(i).name;

    filename{i} = a;

    path = [d,'\',a];

    data = dlmread(path);

    plot(data(:,1), data(:,2),'color',linecolors(i,:),'linewidth',2);

    hold on;

end

hold off;