views:

2666

answers:

3

I'm trying to plot several kernel density estimations on the same graph, and I want them to all be different colors. I have a kludged solution using a string 'rgbcmyk' and stepping through it for each separate plot, but I start having duplicates after 7 iterations. Is there an easier/more efficient way to do this, and with more color options?

for n=1:10
 source(n).data=normrnd(rand()*100,abs(rand()*50),100,1); %generate random data
end
cstring='rgbcmyk'; % color string
figure
hold on
for n=1:length(source)
 [f,x]=ksdensity(source(n).data); % calculate the distribution
 plot(x,f,cstring(mod(n,7)+1))  % plot with a different color each time
end
+6  A: 

you could use a colormap such as HSV to generate a set of color. for example

cc=hsv(12);
figure; 
hold on;
for i=1:12
    plot([0 1],[0 i],'color',cc(i,:));
end

MATLAB has 13 different named colormaps ('doc colormap' lists them all).

Another option for plotting lines in different color is to use the LineStyleOrder property; see Defining the Color of Lines for Plotting in the MATLAB documentation for more information.

Azim
+5  A: 

Actually a decent shortcut method for getting the colors to cycle is to use hold all; in place of hold on;. Each successive plot will rotate (automatically for you) through Matlab's default colormap.

From the Matlab site on hold:

hold all holds the plot and the current line color and line style so that subsequent plotting commands do not reset the ColorOrder and ColorOrder property values to the beginning of the list. Plotting commands continue cycling through the predefined colors and linestyles from where the last plot stopped in the list.

Mark E
A: 

If all vectors have equal size, create a matrix and plot it. Each column is plotted with a different color automatically Then you can use legend to indicate columns:

data = randn(100, 5);

figure;
plot(data);

legend(cellstr(num2str((1:size(data,2))')))

Or, if you have a cell with kernels names, use

legend(names)
Serg

related questions