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

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

Related

Customizing multiple rootlocus plot colors (scale of grey) Matlab

I would like to customize the color of my rootlocus plot.
I use a for cycle to plot 10 rootlocus (with slightly different systems in the loop) and I would like every of them to be of a different shade of grey. I thought to use the gray command to obtain a matrix to store the RGB data and then use this matrix in the rlocus(sys,K,'style') command (choosing the i-th line at the i-th iteration of my cycle). Unfortunately the command requires the style to be a cell (for example 'g' or 'b') and not a vector of numbers.
This is a sample of my code:
figure()
hold on
L = [sys1, sys2, ..., sys10];
colors = gray(10);
for i = 0:9
rlocus (L(i+1), 'Color', colors(i+1, :));
end
The rlocus() function is not as powerful as the plot() function and only has limited support for setting colours with rlocus(sys, 'b') as you've noticed. However, we can combine it with the plot() function to make use of its power.
Here I use [R, K] = rlocus(sys) to return the values of the root locus, R. Each row of R represents a different trajectory. We can plot 1 trajectory of the root locus with plot(R(m, :)) and utilise the strength of plot() to change the colour however we wish.
L = [sys1, sys2, sys3, sys4, sys5, sys6, sys7, sys8, sys9, sys10];
C = gray(numel(L) + 1); % Extra 1 because the last value will be
% white and plotting white on white does
% not look well :P
figure;
hold on
for n = 1:numel(L)
[R, K] = rlocus(L(n));
for m = 1:numel(R)/length(R)
plot(R(m, :), 'Color', C(n, :));
end
end
hold off

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');

Displaying multiple figures with differents colors

I have a matlab code that generates 3D points , so I want to plot each 3D point with different colors.
My last code for generat all points are
figure(i),plot3(mx,my,mz,'r*');
and this one plot all peaks but with same color which are red.
instead of figure(i),plot3(mx,my,mz,'r*'); you can plot each datapoint separately and assign a different color using the property 'Color' of the plot3.
such an example would be:
figure(i),hold on
for j=1:length(mx)
plot3(mx(j),my(j),mz(j),'Color',rand(1,3));
end
hold off
The way each point is coloured is up to you just change the rand to something that makes sense.
What about using e.g. hsv:
M = length(mx);
cols = hsv(M); % specify M colors by hsv
figure(i);
hold on;
for pIdx = 1:M
plot3(mx(pIdx),my(pIdx),mz(pIdx),'Color',cols(pIdx,:));
end

Get access to the default LineStyleOrder and ColorOrder arrays in MATLAB

Quick "convenience" question for MATLAB users. I am looping over a plot command, passing it different data to plot each time. The data happens to be generated from a function call, which upon each iteration is passed a different parameter value. To plot everything on the same axis I am using the 'hold' function. Unfortunately this doesn't auto cycle through the available ColorOrder and/or LineStyleOrder plot parameters, so every line plotted has the same style on every iteration.
for i=1:nLines
[x_data y_data]=get_xy_data(param1(i),param2(i))
plot(x_data,y_data)
end
Every line plotted will be the default blue line style.
The obvious solution is to generate up front a cell array of the various line styles, and colors as in:
line_styles={'-','--','-*'}; %...etc
colors=colormap(jet(nLines));
then access each of those on every iteration. What I want is access to the default colors which will be generated from ColorOrder, and the default line cycling, which comes from LineStyleOrder. If I try something like:
get(gca,'LineStyleOrder')
This only returns the styles used in that axis (I've only tested this on an axis defined with one of the styles, but point is, it doesn't give me all possible linestyles). Help appreciated, thanks!
EDIT: Let me be more specific in what I am looking for.
figure; hold on;
for i=1:nLines
[xdata, ydata]=get_data(p1(i),p2(i)) % call some function to return x,y data
plot(xdata,ydata) % on i=1, default blue line
% function which tells matlab to get/set the next linestyle, color combination
nextStyle()
end
If this doesn't exist, it wouldn't be too hard to write it, but I thought I'd ask first before reinventing the wheel.
You may be interested in setting the default properties of DefaultAxesLineStyleOrder and DefaultAxesColorOrder.
The plots (style and color) will first loop through the newly defined colors and then changed the line style. In a successive plot loop, using hold all will "hold the graph and the current line color and line style so that subsequent plotting commands do not reset the ColorOrder and LineStyleOrder" (see the matlab doc). Both examples produce identical results.
%default properties (line style and color)
set(0,'DefaultAxesLineStyleOrder',{'--','-',':'})
set(0,'DefaultAxesColorOrder', summer(4))
figure('Color','w');
%example plot 1 (concurrent plots)
subplot(1,2,1);
yvals = [1:50;1:50]
plot(yvals, 'LineWidth', 2)
axis([1 2 0 size(yvals,2)+1 ]);
title('concurrent plot','FontSize',16);
%example plot 2 (iterative plots)
subplot(1,2,2);
for ii = 1:50
plot(yvals(:,ii), 'LineWidth', 2);
hold all;
end
axis([1 2 0 size(yvals,2)+1 ]);
title('successive plot','FontSize',16);
The results are
It looks like #Luis Mendo was not that wrong!
You can use hold all. That automatically sets different colors and linestyles for each plot.
You could set the line style and color directly for each line. Here's an example:
figure
hold on
nLines = 12;
line_styles={'-','--','-.'};
colors= hsv(nLines);
indexColors = 1;
indexLines = 1;
for i=1:nLines
xData = 1:10;
yData = rand(1,10);
h = plot(xData,yData);
ls = line_styles{indexLines};
c = colors(indexColors,:);
set(h,'color',c)
set(h,'LineStyle',ls)
if indexColors < length(colors)
indexColors = indexColors + 1;
else
indexColors = 1;
end
if indexLines < length(line_styles)
indexLines = indexLines + 1;
else
indexLines = 1;
end
end

Setting colors for plot function in 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.