user1285419
user1285419

Reputation: 2225

How to specify color for mutliple lines in matlab plot?

I am using the following matlab plot to draw multiple points

plot(ydep, xvar, '.', 'Markersize', 3);

Here ydep and xvar are matrix of 1024x300, so there will be 300 dotted lines being plotted in random color. What my question is how to specify the color for each of 300 lines in the parameter? I try to use a loop to plot each 'line' but that's pretty slow

for n=1:300
  plot(ydep(:, n), xvar(:, n), '.', 'Markersize', 3, 'color', linecolors(n, :));
  hold on;
end

where linecolors defined the color for each of the line.

Upvotes: 0

Views: 10074

Answers (2)

StormRyder
StormRyder

Reputation: 11

I think there's a more convenient way than messing with ColorOrder. The concept of the method is to get the handles of the plotted lines, and then to use the set command. Matlab provides colormaps which can be scaled to the size of your data set, which is very handy here.

I'll modify your example as follows:

h = plot(ydep, xvar, '.', 'Markersize', 3);
set(h,{'color'},num2cell(cool(length(h)),2));

This obtains the handles of all your dotted lines in the first code line. Then I used the colormap cool and scaled it to the same number as the number of elements in h. However, the colormap (which gives a regular matrix) cannot be used in the arguments of the set command directly. One way to specify multiple property values is to use cell arrays, so that's what this example does.

All credit goes to Kelly Kearney for her answer on Matlab Answers.

Upvotes: 0

Dennis Jaheruddin
Dennis Jaheruddin

Reputation: 21563

As mentioned in the comment, the solution is to set the ColorOrder. Then you can just plot it as a matrix with matlabs regular high performance.

Here is an example of how to set the ColorOrder

http://www.mathworks.com/matlabcentral/answers/19815-explicitly-specifying-line-colors-when-plotting-a-matrix

Upvotes: 1

Related Questions