Setting colors for plot function in Matlab - matlab

I would like to be able to choose the colors for a multiline plot but I can not get it. This is my code
colors = {'b','r','g'};
T = [0 1 2]';
column = [2 3];
count = magic(3);
SelecY = count(:,column),
plot(T,SelecY,'Color',colors{column});

For some reason I couldn't get it to work without using a handle, but:
h = plot(T,SelecY);
set(h, {'Color'}, colors(column)');
Works for me.

You can only specify one color at a time that way, and it must be specified as a 3-element RGB vector. Your three routes are:
Loop through and specify the colors by string, like you have them:
hold on
for i=1:size(SelecY, 2)
plot(T, SelecY(:,i), colors{i});
end
Using the RGB color specification, you can pass the colors in via the 'Color' property, like you were trying to do above:
cols = jet(8);
hold on
for i=1:size(SelecY, 2)
plot(T, SelecY(:,i), 'Color', cols(i,:));
end
Also using the RGB way, you can specify the ColorOrder up front, and then let matlab cycle through:
set(gca, 'ColorOrder', jet(3))
hold all
for i=1:size(SelecY, 2)
plot(T, SelecY(:,i));
end
For setting colors after the fact, see the other answer.

Related

Plotting functions in one figure with parameters given by a vector (color issue)

I want to plot four straight lines with different slopes given by a vector $A$:
A=[1.1,2.3,7.9];
k=0;
x=-1:0.01:1;
for n=1:3
plot(x,A(n)*x)
hold on
end
However, it turns out that all lines are of the same color (blue). How do I plot them in different colors, but still using for-end command? (this is necessary when the vector $A$ is huge...)
Actually it can be solved by putting a "hold all" before for-end loop:
A=[1.1,2.3,7.9];
k=0;
x=-1:0.01:1;
hold all
for n=1:3
plot(x,A(n)*x)
end
I am using 2013a. Not sure other versions of Matlab have the same issue and solution.
You could make a colormap (e.g. lines) to specify the colors for all the different lines. By using set on the handle to the lines, you don't have to use a for loop.
A=[1.1,2.3,7.9];
x=-1:0.01:1;
cmap = lines(numel(A));
p = plot(x,A.'*x);
set(p, {'color'}, num2cell(cmap,2));
Alternatively, if you do want to use a for loop, you can set the color using the same colormap, on each loop iteration:
figure()
axes;
hold on;
cmap = lines(numel(A));
for n = 1:numel(A)
plot(x,A(n)*x, 'Color', cmap(n,:));
end
Use the following
A=[1.1 2.3 7.9];
x=[-1 1]; % use this instead of x=-1:0.01:1
line(x,A'*x);
result:
Also, if you wish to manipulate the colors manually, use the following code:
A=[1.1 2.3 7.9];
L=length(A);
col_mat=rand(L,3); % define an arbitrary color matrix in RGB format
x=[-1 1]; % use this instead of x=-1:0.01:1
p=line(x,A'*x);
%% apply the colors
for i=1:L
p(i).Color=col_mat(i,:);
end

Matlab: same colormap for hist, plot and mesh

I have datasets for 5 different frequencies in a matrix and I want to illustrate them using plot, hist and mesh. However, each plot type is using different colormaps (see picture), so I need a legend for every plot.
Is there a way to set the same colormap for all plot types, or specify one for each of them? Another thing thats strange: I can set the colormap for hist using the figure tools for example, but not for the normal plot. For the mesh I have to use a hold on loop, so I guess setting the color here is different from defining a colormap?
Edit:
Here is a minimal example. Its still not working, see comments in the code below.
clear all;
close all;
clc;
% make up some data with the original format
freqLen = 5;
data = zeros(10, 3, 3, freqLen);
data(:, :, :, 1) = rand(10, 3, 3);
data(:, :, :, 2) = rand(10, 3, 3)+1;
data(:, :, :, 3) = rand(10, 3, 3)+2;
data(:, :, :, 4) = rand(10, 3, 3)+3;
data(:, :, :, 5) = rand(10, 3, 3)+4;
% reshape data so we get a vector for each frequency
dataF = reshape(data, [10*3*3, freqLen]);
% prepare colors for plot, try to get 5 colors over the range of colormap
% but I get wrong colors using both methods below!
%cols = colormap(jet);
%cols = cols(1:round(length(cols)/length(freqGHz)):end, :);
cols = jet(freqLen);
% plot samples in 3D
figure('Position', [0 0 1000 1000]);
subplot(211);
hold on;
for iF = 1:freqLen
dataThisF = dataF(:, iF);
data3D = reshape(dataThisF, [10*3, 3]);
mesh(data3D);
% try to give each "holded" mesh a different color. Not working!
% after the loop, all meshes have the last color
set(get(gca, 'child'), 'FaceColor', 'w', 'EdgeColor', cols(iF, :));
end
view(60, 20);
% plot samples
subplot(223);
hold on;
for iF = 1:freqLen
% the loop is not avoidable
% because matlab maps the colors wrong when plotting as a matrix
% at least its not using the colormap colors
plot(dataF(:, iF), 'Color', cols(iF, :));
end
% plot histogram
subplot(224);
% actually the only one which is working as intended, horray!
hist(dataF, 50);
How can I give a holded mesh a single color, different from the others? How can I map the correct jet colormap when plotting a matrix using simple line plot, or at least get 5 colors from the jet colormap (jet(5) give 5 different colors, but not from start to end)?
What you are talking about is mainly the ColorOrder property (and not the colormap of the figure).
The link for the colororder given just above will explain you how to force Matlab to use a given set of colors for all the plots. It works perfectly fine for plot. You wouldn't need a loop, just define the DefaultColororder property of the figure before the plots then plot all your series in one single call, Matlab will assign the color of each plot according to the order you defined earlier.
For mesh and hist it is not that simple unfortunately, so you will have to run a loop to specify the color or each graphic object. To modify a graphic object property (like the color) after it has been created, you have to use the set method, or even the direct dot notation if you're using a Matlab version >= 2014b. For both methods you needs to have the handle of the graphic object, so usually the easiest when you know you'll need that is to retrieve the graphic object handle at the time of creation*.
*instead of dirty hack like get(gca, 'child'). This is quite prone to errors and as a matter of fact was wrong in your case. Your code wouldn't color properly because you were not getting the right graphic handle this way.
The code below plots all your graphs, retrieve the handle of each graphic object, then assign the colors in the final loop.
%// Get a few colors
cols = jet(freqLen);
% plot samples in 3D
figure('Position', [0 0 1000 1000]);
set( gcf , 'DefaultAxesColorOrder',cols) %// set the line color order for this figure
subplot(2,1,1,'NextPlot','add'); %// 'NextPlot','add' == "hold on" ;
for iF = 1:freqLen
dataThisF = dataF(:, iF);
data3D = reshape(dataThisF, [10*3, 3]);
h.mesh(iF) = mesh(data3D) ; %// plot MESH and retrieve handles
%// You can set the color here direct, or in the last final "coloring" loop
%// set( h.mesh(iF) , 'FaceColor', 'w', 'EdgeColor', cols(iF, :));
end
view(60, 20);
%// plot samples
subplot(223);
h.plots = plot(dataF); %// plot LINES and retrieve handles
%// plot histogram
subplot(224);
[counts,centers] = hist(dataF, 50 ) ; %// get the counts values for each series
h.hist = bar(centers,counts) ; %// plot HISTOGRAM and retrieve handles
%// now color every series with the same color
for iF = 1:freqLen
thisColor = cols(iF, :) ;
set( h.mesh(iF) , 'EdgeColor' , thisColor , 'FaceColor', 'w' );
set( h.hist(iF) , 'EdgeColor' , thisColor , 'FaceColor' , thisColor )
%// this is actually redundant, the colors of the plots were already right from the
%// beginning thanks to the "DefaultColorOrder" property we specified earlier
set( h.plots(iF) , 'Color' , thisColor )
end
Will land you the following figure:
UPDATE: The original question asked
Is there a way to set the same colormap for all plot types, or specify one for each of them?
this answer, answers that question with colormap taken to mean colormap in MATLAB literally.
You can set the colormap for a figure using colormap. You could use one of the many built in colormaps or specify your own.
An example using mesh and the builtin hsv colormap could be
figure;
mesh(data);
colormap(hsv);
This would apply a colormap based on
to your figure. You can also create your own colormap like
map = [1, 0, 0,
1, 1, 1,
0, 1, 0,
0, 0, 0];
colormap(map);
which would create a colormap with the colours Red, White, Blue and Black.
The MATLAB documentation contains extensive information on the use of colormap.

Reset ColorOrder index for plotting in Matlab / Octave

I have matrices x1, x2, ... containing variable number of row vectors.
I do successive plots
figure
hold all % or hold on
plot(x1')
plot(x2')
plot(x3')
Matlab or octave normally iterates through ColorOrder and plot each line in different color. But I want each plot command to start again with the first color in colororder, so in default case the first vector from matrix should be blue, second in green, third in red etc.
Unfortunately I cannot find any property related to the color index niether another method to reset it.
Starting from R2014b there's a simple way to restart your color order.
Insert this line every time you need to reset the color order.
set(gca,'ColorOrderIndex',1)
or
ax = gca;
ax.ColorOrderIndex = 1;
see:
http://au.mathworks.com/help/matlab/graphics_transition/why-are-plot-lines-different-colors.html
You can shift the original ColorOrder in current axes so that the new plot starts from the same color:
h=plot(x1');
set(gca, 'ColorOrder', circshift(get(gca, 'ColorOrder'), numel(h)))
plot(x2');
You can wrap it in a function:
function h=plotc(X, varargin)
h=plot(X, varargin{:});
set(gca, 'ColorOrder', circshift(get(gca, 'ColorOrder'), numel(h)));
if nargout==0,
clear h
end
end
and call
hold all
plotc(x1')
plotc(x2')
plotc(x3')
Define a function that intercepts the call to plot and sets 'ColorOrderIndex' to 1 before doing the actual plot.
function plot(varargin)
if strcmp(class(varargin{1}), 'matlab.graphics.axis.Axes')
h = varargin{1}; %// axes are specified
else
h = gca; %// axes are not specified: use current axes
end
set(h, 'ColorOrderIndex', 1) %// reset color index
builtin('plot', (varargin{:})) %// call builtin plot function
I have tested this in Matlab R2014b.
I found a link where a guy eventually solves this. He uses this code:
t = linspace(0,1,lineCount)';
s = 1/2 + zeros(lineCount,1);
v = 0.8*ones(lineCount,1);
lineColors = colormap(squeeze(hsv2rgb(t,s,v)))
ax=gca
ax.ColorOrder = lineColors;
Which should work for you assuming each of your matrices has the same number of lines. If they don't, then I have a feeling you're going to have to loop and plot each line separately using lineColors above to specify an RBG triple for the 'Color' linespec property of plot. So you could maybe use a function like this:
function h = plot_colors(X, lineCount, varargin)
%// For more control - move these four lines outside of the function and make replace lineCount as a parameter with lineColors
t = linspace(0,1,lineCount)'; %//'
s = 1/2 + zeros(lineCount,1);
v = 0.8*ones(lineCount,1);
lineColors = colormap(squeeze(hsv2rgb(t,s,v)));
for row = 1:size(X,1)
h = plot(X(row, :), 'Color', lineColors(row,:), varargin{:}); %// Assuming I've remembered how to use it correctly, varargin should mean you can still pass in all the normal plot parameters like line width and '-' etc
hold on;
end
end
where lineCount is the largest number of lines amongst your x matrices
If you want a slightly hacky, minimal lines-of-code approach perhaps you could plot an appropriate number of (0,0) dots at the end of each matrix plot to nudge your colourorder back to the beginning - it's like Mohsen Nosratinia's solution but less elegant...
Assuming there are seven colours to cycle through like in matlab you could do something like this
% number of colours in ColorOrder
nco = 7;
% plot matrix 1
plot(x1');
% work out how many empty plots are needed and plot them
nep = nco - mod(size(x1,1), nco); plot(zeros(nep,nep));
% plot matrix 2
plot(x2');
...
% cover up the coloured dots with a black one at the end
plot(0,0,'k');

How can I change the color of bars in bar graph?

I'd like to create a bar graph where I change the color of some bars.
The code for my bar graph is the following:
y = [0.04552309, -0.001730885, 0.023943445, 0.065564478, 0.032253892, 0.013442562, ...
-0.011172323, 0.024595622, -0.100614203, -0.001444697, 0.019383706, 0.890249809];
bar(y)
I want the first six bars to be black and the last 6 bars to be blue, but I have no idea how to do it.
You need to plot them separately (but on the same axes):
bar(1:6,y(1:6),'k')
hold on
bar(7:numel(y),y(7:end),'b')
set(gca,'xtick',1:numel(y))
As the answer from HERE suggests, since the version MATLAB R2017b, you can do so through the CData property. You can find more at THIS documentation page.
Simply put, using the following approach will get you what you need.
b = bar(rand(10,1));
b.FaceColor = 'flat';
% Change the color of the second bar. Value assigned defines RGB color value.
b.CData(2,:) = [.5 0 .5];
The following is adapted from Bar plot with bars in different colors on MATLAB Central:
y= [0.04552309, -0.001730885, 0.023943445, 0.065564478, 0.032253892, 0.013442562, -0.011172323, 0.024595622, -0.100614203, -0.001444697, 0.019383706, 0.890249809];
for ii=1:12
h = bar(ii-0.5, y(ii));
if ii == 1
hold on
end
if ii<=6
col = 'k';
else
col = 'b';
end
set(h, 'FaceColor', col,'BarWidth',0.4)
end
axis([0 12 -0.2 1])
hold off
No need to plot separately, here is the simple solution:
y= [0.04552309, -0.001730885, 0.023943445, 0.065564478, 0.032253892, 0.013442562, -0.011172323, 0.024595622, -0.100614203, -0.001444697, 0.019383706, 0.890249809];
figure,
bar(y)
y1 = zeros(1,length(y));
y1(3:5) = y(3:5);
hold on
h = bar(y1)
set(h, 'FaceColor', 'k')
See output
Very late as usual, but there is an easy way to 'trick' matlab.
You first define your colormap (for instance 3 different colors):
mycolors = lines(3) % or just specify each row by hand
Then you plot your bars in the following way:
bar(x,diag(y),'stacked'); % x will be usually defined as x = 1:number_of_bars
colormap(mycolors);
That's all. The magic comes from the diag function together with the 'stacked' tag that makes matlab think you have more data (but they are all 0).

How do I plot values from a struct as different lines so I can control their color Matlab?

What I want:
Different coloured points on a plot and to have the points in a legend with their respective colours.
I tried this:
I have created a struct which contains x, y values of points. With these points I hope to plot points on an image so I can see where they are. However, as I'm using a struct I can't get the plot to make the points in different colours. With the for loop I tried to coax matlab in creating multiple plots, and hopefully different lines, which I could then assign to different colours of my choosing.
Code:
img = imread('retinotopische map V1M Base clean.bmp');
hold on;
image([0.825 4.61],[-2.85 ,-8.25],img);
for A = 1:B
plot( [c(A).Lateral],[c(A).Bregma],'o','MarkerSize',10);
plot( [c(A).Lateral],[c(A).Bregma],'.','MarkerSize',10);
end
If you just want different colors, the solution is easier than you would expect:
Replace hold on with hold all and matlab will automatically use the next color.
Edit: If you start a new plot, you may need to call hold off and hold all again to get the right starting position.
You can change the colour using the 'Color' option:
img = imread('retinotopische map V1M Base clean.bmp');
hold on;
image([0.825 4.61],[-2.85 ,-8.25],img);
for A = 1:B
plot( [c(A).Lateral],[c(A).Bregma],'o','MarkerSize',10, 'Color', [A/B, 0, 1 - A/B]);
end
'Color' lets you specify an RGB triple like [1 0 0] for red for example. You can use this to plot whatever colors you want. My example will plot them in like a gradient but you could also have totally different colours using say rand(1, 3) to get the triple? Or else make a colour matrix where you specify the exact order of colours you want like:
MyColours = [1 1 0;
0 0 1;
1 0 0;
0.5 0.2 0.9]; %etc...
and then in your for loop:
plot( [c(A).Lateral],[c(A).Bregma],'o','MarkerSize',10, 'Color', MyColours(A, :));