How do I plot values from a struct as different lines so I can control their color Matlab? - 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, :));

Related

Plotting a phase portrait with multiple colors with MATLAB

I want to add something to make my phase portrait more understandable. Nevertheless, I can't find anything (I found this
https://se.mathworks.com/help/matlab/ref/colorspec.html
https://se.mathworks.com/matlabcentral/fileexchange/11611-linear-2d-plot-with-rainbow-color
https://se.mathworks.com/help/symbolic/mupad_ref/linecolortype.html
) but it is not what I need.
I would really like to see the color of the line of the phase portrait changing depending of if it is at the beginning or at the end of the simulation.
I found this idea which seems great :
I don't understand at all what he has done (the code is I suppose written here:
https://blogs.mathworks.com/pick/2008/08/15/colors-for-your-multi-line-plots/ )
but It would be great if I can plot a one line function which color varies depending of the time. If moreover, like on the picture, I can have have a scale on the right: it would be awesome.
So for now, I have that :
data = readtable('test.txt');
figure('Name','Phase' , 'units','normalized','outerposition',[(8/100) (0.3- 16/100) 0.5 0.7]);
hold on
plot(data{:,2},data{:,3}, 'k.', 'LineWidth',1.5 );
plot(data{:,4},data{:,5}, 'r.', 'LineWidth',1.5 );
xL = xlim;
yL = ylim;
line([0 0], yL); %x-axis
line(xL, [0 0]); %y-axis
title(['Phase portrait'])
xlabel('f')
ylabel('f '' ')
hold off
I read the values of the function in a .txt file, and then I plot the 2nd/3rd columns and 4/5th columns. The first column is the time evoluting.
Do you have any idea :)?
Thank you!
There are several ways to go about this to be honest.
However it makes a bit easier if you let us know what your time data is.
Do you plot your time data on the x (or y) axis or is it a different additional data set. Should it be an additional data set then you can consider it like z-data, plotted on the Z-axis or/and as a color.
Below is an example of what you can do by making a 3D plot but displaying it in 2D, this allows you to add the colorbar without too many problems.
x=0:5;
y=0:5;
z=rand(1,6); %random data to simulate your time
xx=[x' x']; %this allows you to plot the data using surf in 3d
yy=[y' y']; %same as for xx
z1=zeros(size(xx)); % we don't need z-data so we're making it a matrix of zeros
zc=[z' z']; %input here your time data values, if x/y then you can just use those instead of z
hs=surf(xx,yy,z1,zc,'EdgeColor','interp') %// color binded to "z" values, choose interp for interpolated/gradual color changes, flat makes it sudden
colormap('hsv') %choose your colormap or make it yourself
view(2) %// view(0,90)
hcb=colorbar; %add a colorbar
I found this, thanks to another user on stackoverflaw.
data = readtable('4ressorspendule.txt');
n = numel(data.Var1);
c = size(data,2);
figure('Name','Phase' , 'units','normalized','outerposition',[(8/100) (0.3 - 16/100) 0.5 0.7]);
for i=1:n
hold on
plot(data{i,2},data{i,3},'.','Color',[1 (1-i/n) 0] ,'MarkerSize',4);
plot(data{i,4},data{i,5},'.','Color',[0 (i/n) (1-i/n)],'MarkerSize',4);
end
xL = xlim;
yL = ylim;
line([0 0], yL); %x-axis
line(xL, [0 0]); %y-axis
title(['Phase portrait'])
xlabel('f')
ylabel('f '' ')
hold off

Vary color across plot points

The following code plots 3 points, all in red:
a = reshape([92.571251 94.869889 97.283709 ],[3 1]);
b = reshape([271.000000 296.000000 330.000000 ],[3 1]);
c = reshape([0.916000 0.766000 0.562000 ],[3 1]);
figure(100);
line(b,a,...
'MarkerFaceColor',[1 0 0],...
'Marker','o',...
'LineStyle','none',...
'Color',[1 0 0]);
Is there a way for me to vectorize the red portion of the 'Color' plot style using 'c' such that the first point uses c(1) to replace the 1 so that the color is [0.916 0 0], etc.?
NOTE: This code is a snippet of something much larger that will likely plot 100's or 1000's of points over time on the same plot. I need the color for each point to be set when it's placed on the plot and then not change as other points are added. (If possible)
I do not think a color map is appropriate as I may plot points at the same X,Y coordinates at different times. Sometimes they will be bright, other times dim.
Just trying to not use a loop which would be relatively straight forward.
Thanks!
To colorize the points (and only the points, not the lines in between), you can use the MarkerFaceColor property of the scatter function (or scatter3 in 3D).
For instance:
scatter(a, b, 'MarkerFaceColor', rgb)
where rgb are RGB triplets, or
scatter(a, b, 'MarkerFaceColor', 'flat', 'CData', c)
with c being a vector of values. In this case the colors are mapped onto the current colormap and the range is controled by caxis.
If you want lines between your points, you can simply use a code like this:
hold on
plot(a, b, '-')
scatter(...)
Best,

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

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.

Matlab Ploting with different color for iso-surface

I was trying use the code shown below to plot in such a way that each iso-surface will be different in color and there will be a color bar at the right. I made a ss(k) color matrix for different colors. Number of iso-surfaces is 10 but I have only 8 colors. That's why I wrote ss(9)='r' and ss(10)='r'.
I need a solution to plot the iso-surface with different color and bar at the right side.
ss=['y','m','c','r','g','b','w','k','r','r']
k=1;
for i=.1:.1:1
p=patch(isosurface(x,y,z,v,i));
isonormals(x,y,z,v,p)
hold on;
set(p,'FaceColor',ss(k),'EdgeColor','none');
daspect([1,1,1])
view(3); axis tight
camlight
lighting gouraud
k=k+1;
end
Another possibility is to draw the patches with direct color-mapping (by setting the property 'CDataMapping'='direct'), while assigning the 'CData' of each patch to an index in the colormap of your choice. This is in fact recommended for maximum graphics performance.
Consider the following example:
%# volumetric data, and iso-levels we want to visualize
[x,y,z,v] = flow(25);
isovalues = linspace(-2.5,1.5,6);
num = numel(isovalues);
%# plot isosurfaces at each level, using direct color mapping
figure('Renderer','opengl')
p = zeros(num,1);
for i=1:num
p(i) = patch( isosurface(x,y,z,v,isovalues(i)) );
isonormals(x,y,z,v,p(i))
set(p(i), 'CData',i);
end
set(p, 'CDataMapping','direct', 'FaceColor','flat', 'EdgeColor','none')
%# define the colormap
clr = hsv(num);
colormap(clr)
%# legend of the isolevels
%#legend(p, num2str(isovalues(:)), ...
%# 'Location','North', 'Orientation','horizontal')
%# fix the colorbar to show iso-levels and their corresponding color
caxis([0 num])
colorbar('YTick',(1:num)-0.5, 'YTickLabel',num2str(isovalues(:)))
%# tweak the plot and view
box on; grid on; axis tight; daspect([1 1 1])
view(3); camproj perspective
camlight; lighting gouraud; alpha(0.75);
rotate3d on
I also included (commented) code to display the legend, but I found it to be redundant, and a colorbar looks nicer.
Matlab usually plots different iso-surfaces in different colors automatically, so you don't need to care about that. What kind of bar do you need? A colorbar or a legend? Either way, it is just to use the colorbar or legend function..
%Create some nice data
[x y z] = meshgrid(1:5,1:5,1:5);
v = ones(5,5,5);
for i=1:5
v(:,:,i)=i;
end
v(1:5,3:5,2)=1
v(1:5,4:5,3)=2
%Plot data
for i=1:5
isosurface(x,y,z,v,i)
end
%Add legend and/or colorbar
legend('one','Two','Three','Four')
colorbar
Since the color bar encodes value->color, it is impossible to do what you ask for, unless there is no intersection in z-values between all pairs of surfaces. So the solution below assumes this is the case. If this is not the case, you can still achieve it by adding a constant value to each surface, so to separate the surfaces along the z axis, and eliminate any intersection.
The solution is based on constructing a colormap matrix of piecewise constant values, distributed similarly to the z values of your surfaces. So for example, if you have 3 surfaces, the first has z values between 1 and 10, the 2nd between 11 and 30, and the 3rd between 31 and 60, you should do something like this (I plot in 2D for simplicity)
r = [1 0 0];
g = [0 1 0];
b = [0 0 1];
cmap = [r(ones(10,1),:); g(ones(20,1),:); b(ones(30,1),:)];
z1 = 1:10;
z2 = 11:30;
z3 = 31:60;
figure; hold on
plot(z1,'color',r)
plot(z2,'color',g)
plot(z3,'color',b)
colorbar
colormap(cmap)
More complex colormaps (i.e, more colors) can be constructed with different mixtures of red, green, and blue (http://www.mathworks.com/help/techdoc/ref/colorspec.html)