Explicitly specifying line colors when plotting a matrix

x = 1:3;
y = [1 2 3; 42 40 34];
plot(x,y,'Color', [0.5 0.5 0.5; 1 0 0])
produce an error:
Error using plot
Color value must be a 3 element numeric vector
Same with:
plot(x,y,'rg')
Error using plot
Error in color/linetype argument
This has bugged me for years, but I have circumvented it by unrolling the matrix into a number of vectors that I plot one at a time using whatever color I prefer. But is there no way to tell MATLAB (in a compact, readable form) what colors I would like it to use for whatever number of lines it will plot?

1 Comment

You can make a for loop and specify each line's colour based on the RGB code:
x = 1:3;
y = [22 20 18; 32 30 24; 42 40 34];
figure
hold on
for k=1:size(y,1)
p(k)=plot(x,y(k,1:end),'LineWidth',2);
set(p(k),'Color',[(size(y,1)-k+1)/size(y,1) k/size(y,1) 0.1]);
end

Sign in to comment.

 Accepted Answer

An alternative method would be to save the handles of the plotted data and set the colors via the array option of set. I find this method a lot less hassle than messing with ColorOrder and hold states:
x = 1:3;
y = [1 2 3; 42 40 34];
h = plot(x,y);
set(h, {'color'}, {[0.5 0.5 0.5]; [1 0 0]});
I often use the shortcut of using a colormap with num2cell to get the desired list of colors:
set(h, {'color'}, num2cell(jet(2),2));

7 Comments

Dear Kelly (or anyone else reading this),
Could you please "unpack" this answer a bit more? This method is exactly what I'm looking for, because I'm creating line plots with something like 50-100 curves at a time, and I want the colors between each curve to vary sequentially, from first to last curve in the data set. Hence, using a colormap is perfect. I got it to work by following your template and changing the argument in jet() to the total number of curves that I'm plotting.
However, I don't quite get why it's necessary to use cells in the argument of the set() function.
I believe I answered your question in my demo attached in the 3rd (hidden) comment above: https://www.mathworks.com/matlabcentral/answers/19815-explicitly-specifying-line-colors-when-plotting-a-matrix#comment_241391 Show all the comments and look for colororder_demo. Actually, I'm just going to attach them here again.
The cell arrays are used because I'm using the cell array syntax for set, as described in the help text for that function (third option):
"set(H,pn,pv) sets the named properties specified in the cell array of strings pn to the corresponding values in the cell array pv for all objects specified in H. The cell array pn must be 1-by-N, but the cell array pv can be M-by-N where M is equal to length(H) so that each object will be updated with a different set of values for the list of property names contained in pn."
I could also set multiple properties using this syntax:
set(h, {'color', 'linewidth'}, [num2cell(jet(2),2) num2cell((1:length(h))')]);
Thanks for sharing! It is extremely helpful!
I regret for not seeing this earlier! Thank you for sharing!
Since 2019 there is an easier way to do this by setting your own color order by using the colororder command.
x = 1:3;
y = [1 2 3; 42 40 34];
colororder([0 0 1; 0.5 0.6 0])
plot(x,y)
Building on @Simon Silge's response, one can also use colororder with the preset colors (e.g., 'k', 'r', 'b', etc) if they're provided as a cell array:
x = 1:3;
y = [1 2 3; 42 40 34];
colororder({'r', 'b'})
plot(x, y)

Sign in to comment.

More Answers (3)

In the help it says this:
"plot automatically chooses colors and line styles in the order specified by ColorOrder and LineStyleOrder properties of current axes. ColorOrder : m-by-3 matrix of RGB values
Colors to use for multiline plots. Defines the colors used by the plot and plot3 functions to color each line plotted. If you do not specify a line color with plot and plot3, these functions cycle through the ColorOrder property to obtain the color for each line plotted. To obtain the current ColorOrder, which might be set during startup, get the property value:
get(gca,'ColorOrder')
Note that if the axes NextPlot property is replace (the default), high-level functions like plot reset the ColorOrder property before determining the colors to use. If you want MATLAB to use a ColorOrder that is different from the default, set NextPlot to replacechildren. You can also specify your own default ColorOrder."
co = get(gca,'ColorOrder') % Initial
% Change to new colors.
set(gca, 'ColorOrder', [0.5 0.5 0.5; 1 0 0], 'NextPlot', 'replacechildren');
co = get(gca,'ColorOrder') % Verify it changed
% Now plot with changed colors.
x = 1:3;
y = [1 2 3; 42 40 34];
plot(x,y, 'LineWidth', 3);
The things I put in the set() command are especially important.

6 Comments

Thank you, really helpful.
3 years later this answer is still helping people. :)
Here's something that will probably be even more helpful. I'm attaching my colororder demo to show you how you can change the default colors to whatever you want.
oh, it's work on subplot, too thank you~
A note for subplot: need to put the set line before each plot command
x = 1:3;
y1 = [1 2 3; 42 40 34];
y2 = [3 5 8; 11 17 29];
subplot(2,1,1);
set(gca, 'ColorOrder', [0.5 0.5 0.5; 0.2 0.2 0.2],'NextPlot', 'replacechildren');
plot(x,y1, 'LineWidth', 3);
subplot(2,1,2);
set(gca, 'ColorOrder', [0.5 0.5 0.5; 0.2 0.2 0.2],'NextPlot', 'replacechildren');
plot(x,y2, 'LineWidth', 3);
And much appreciated to Image Analyst!
And if you need to restore the color order to the defaults, use reset(gca).

Sign in to comment.

I can solve your problem with something like this:
x = 1:5;
y = [x; x.^2; x.^3; x.^4; x.^5];
n = size(y, 1);
colors = hsv(n);
h = plot(x, y);
set(h, {'color'}, num2cell(colors, 2));

2 Comments

just great! thanks a lot!
Hi, works perfectly, thank you. I have a follow-up question to this. Is it possible that I can have the colors based on a different data set? i.e. I use X and Y only for plotting but the colors of the plot are based on data set, say P (Pressures).

Sign in to comment.

It is beyond me how matlab manages to be so unintuitive in the most simple sitiations. Luckily there is a smart community that can find workarounds for all of these shortcomings. Someone above stated happily that this answer is still helping people years after it was asked, too me this is just sad, that Mathworks haven't improved this in all of that time.

3 Comments

Joakim, I partially agree with you. In my (limited) experience, MATLAB is much more intuitive than its competitors. If you think MATLAB is difficult, try R! However, this example shows that there is plenty of scope for improvement.
I agree with you, Joakim. I think by now it should be possible to do something like "plot(x,Y, 'color', C), where Y is a matrix, and C contains as many colors as there will be lines.
@Jolanda Müller you simply need to call the colororder function first before calling plot, instead of passing your colors into plot. It's hardly a horrendous hassle or even a "workaround". It's just a different way of doing things and only requires one line of code to tell it to use your custom colors.
numCurves = 20;
numPointsPerCurve = 10;
% Create matrix of data. Individual curves are in columns.
M = rand(numCurves, numPointsPerCurve);
% Create matrix of custom colors for each curve.
C = rand(numCurves, 3); % Just random colors.
colororder(C); % Tell MATLAB to use these custom colors.
% Plot 20 curves, each with it's own unique custom color.
plot(M, '.-', 'LineWidth', 2)

Sign in to comment.

Categories

Find more on Creating, Deleting, and Querying Graphics Objects in Help Center and File Exchange

Products

Asked:

on 30 Oct 2011

Commented:

on 25 Sep 2023

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!