Matlab colormap line plot

廉价感情. 提交于 2019-12-11 07:27:38

问题


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:


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

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;


来源:https://stackoverflow.com/questions/28673677/matlab-colormap-line-plot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!