How to plot 2D data with different colors and markers - matlab

Im faced with a problem where i need to plot a two dimensional data with different colors and markers.
We are given with 2 array, namely points (n x 2 dimension) and Label (n x 1 dimension). Im not sure about the number of unique values in the Label array but maximum could be 10. I would like to plot the points with different color and markers based on its corresponding Label value.
Can any one help me in this regard

Use gscatter, which does a scatter plot, using a group (Label in your case) to plot in different colours/makers.
GSCATTER(X,Y,G,CLR,SYM,SIZ) specifies the colors, markers, and
size to use. CLR is either a string of color specifications or
a three-column matrix of color specifications. SYM is a string
of marker specifications. Type "help plot" for more information.
For example, if SYM='o+x', the first group will be plotted with a
circle, the second with plus, and the third with x. SIZ is a
marker size to use for all plots. By default, the marker is '.'.
So you can specify colours like 'rgcmykwb' to do red for the first group, green for the second, etc or [] just to have Matlab sort it out.
By default Matlab uses the same marker for each group, so you need to specify what markers you want to be used for each group. If you do '.ox+*sdv^<>ph' you'll just cycle along all the markers that Matlab has.
n=50;
% make nx2 matrix of random points.
points = random('unif',0,1,n,2);
% make nx1 matrix of random labels from {1,2,...,5}
labels=round(random('unif',1,5,n,1));
% plot. Let Matlab sort out the colours and we will specify markers.
gscatter(points(:,1),points(:,2),labels,[],'ox+*sdv^<>ph.')
It looks a bit like this:

Related

plotting a text file with 4 columns in matlab

I want to plot a text file with 4 columns that first column in longitude,second in latitude, third is depth and forth is amount of displacement in each point.(it's related to a fualt)
-114.903874 41.207504 1.446784 2.323745
I want a plot to show the amount of displacement in each point (like images that we plot with imagesc),unfortunately "imagesc" command doesn't work for it.
how can I plot it?
Thanks for your attention
A simple way would be to use scatter3 and assign your displacements to be the colours. Note that you have to supply a size for this to work - I'm using [] (empty matrix) which will set it to default. If your four sets of values are four vectors of the same size, then it's just something like:
scatter3(lat,lon,depth,[],displacement, 'filled')
Values in displacement will be linearly mapped to the current colormap. 'filled' gives you filled markers rather than open ones (default marker is a circle but can be changed).
You can plot each point using plot3(longitude,latitude,depth). You can color each point according to the displacement in a for loop. The easiest way to do this is create a colormap, e.g. using jet and chosing the color according to the displacement.
figure;
hold on;
cmap = jet(256);
dispRange = [min(displacement),max(displacement)];
for k=1:size(longitude,2)
c = cmap(1+round(size(cmap,1)*(displacement(k)-dispRange(1))/dispRange(2)),:);
plot3(longitude(k),latitude(k),depth(k),'o', ...
'MarkerEdgeColor',c,'MarkerFaceColor',c);
end

Create a network without bioinformatics tool box?

I have a matrix consisting of three rows: gene 1, gene 2, Distance.
I want to create a network where each gene is a node and the connecting line is scaled by the distance between the two genes.
How can I do this without using the bioinformatics or neural network toolboxes?
Thanks!
Some Information
It is almost impossible to draw a graph with edge length proportional to edge weight, atleast its very unlikely that the weights allow a graph to be drawn this way, most will be impossible...
See:
P. Eades and N. C. Wormald. Fixed edge-length graph drawing is
NP-hard. Discrete Applied Mathematics, 28(2):111–134, 1990]
or to quote:
"Drawing planar graphs with edge weights as standard node-link
diagram, where edge lengths are proportional to the edge weights, is
an NP-hard problem"
M. Nollenburg, R. Prutkin and I. Rutter, Edge-weighted contact
representations of planar
graphs.
Journal of Graph Algorithms and Applications, 17(4):441–473, 2013
Consider the simple example of the 3 vertices joined as such, in your data format:
[1,2,1;
1,3,1;
2,3,10;]
it's should be immediately obvious that such a graph is impossible to draw with edge length proportional to weight (with straight lines). As such alternatives in MATLAB include using color or line width to represent Weight.
Sorry for the length of this answer but to implement this is not trivial, the process used below for drawing the graph can also be found here (in debth), here (most simple) and in a similar problem here. However these do not address weighted graphs...
So on with implementing line width and color proportional to weight:
Code
Due to the length the code is available without description here
Firstly some test data, consisting of 30 edges randomly assigned between 20 vertices with random weights between 0 and 10.
clear
%% generate testing data
[X,Y] = ndgrid(1:20); testdata = [X(:) Y(:)]; %// all possible edges
data(data(:,1)==data(:,2),:)=[]; %// delete self loops
data=data(randperm(size(data,1),20),:); %// take random sample of edges
data(:,3)=rand(size(data,1),1)*10; %// assign random weights in range 0-10
First some processing of the data to get it into required format;
edges=data(:,1:2);
[Verticies,~,indEdges]=unique(edges); %// get labels & locations of vertices
indEdges=reshape(indEdges,[],2);
weights=data(:,3);
normalisedWeights=weights/max(weights); %// normalise weights (range 0-1)
numeEdge=numel(weights);
numVertex=numel(Verticies);
Now x and y coordinates for each vertex are created on a unit circle:
theta=linspace(0,2*pi,numVertex+1);
theta=theta(1:end-1);
[x,y]=pol2cart(theta,1); % create x,y coordinates for each vertex
As lines in MATLAB plots inherit their color from the axis color order we create a RGB array which corresponds to a colormap, with a entry for each line giving the RGB values for the color assigned to that weight.
The autumn colormap is simple to manually implement as R=1,B=0 for all values and G ranges from 0-1 linearly, so we can make the Cmap variable which is used as the axis color order as follows:
clear Cmap %// to avoid errors due to the way it is created
Cmap(:,2)=normalisedWeights;
Cmap(:,1)=1;
Cmap(:,3)=0;
Now we create a figure, set the colormap to autumn (for the color bar), put hold on so the plot command doesn't reset the color order, and apply the color order
figure
colormap('autumn')
hold on
set(gca,'colororder',Cmap) %// set axis colororder to Cmap
how we plot the edges using the edge indexes generated earlier at locations given by x & y. The handles of the lines (Hline) is stored for later use.
Hline=plot(x(indEdges).',y(indEdges).'); %// plot edges
Now we set the axis to square so the circle of points is displayed properly and turn the axis off to hide them (as they bear no relevance to the plotted graph). The axis color limits (Clim) is then set to match the range of weights and add a colorbar is added.
axis square off
set(gca,'Clim',[0 max(weights)])
colorbar
The final step for plotting the edges, setting the line width to be proportional to weight, The normalised weights are scaled to be in the range 0-5. The linewidths are then set to scalefactor*normalisedWeights..
scalefactor=5; %// scale factor (width of highest weight line)
set(hline, {'LineWidth'}, num2cell(normalisedWeights*scalefactor));
The vertices are now plotted at the x and y coordinates (as black squares here).
The axis limits are increased to allow vertex labels to fit. Finally the vertices are labelled with the values from the original matrix, the labels are placed on a slightly larger circle than the vertices
plot(x,y,'ks')
xlim([-1.1,1.1]) % expand axis to fix labels
ylim([-1.1,1.1])
text(x(:)*1.1, y(:)*1.1, num2str(Verticies),...
'FontSize',8,'HorizontalAlignment','center'); %// add Vertex labels
Results

MATLAB: Plotting Contours at Specfic Points (x,y)

I'm currently producing a contour plot using
contour(x,y,z)
However, I would like to specify some additional contour lines to the ones provided.
I understand that I can use contour(x,y,z,v) where v is some vector containing values of the contour levels I would like but I don't really want to use this since I don't know exactly the levels.
Instead is it possible to plot the contour that goes through a specific point (x,y)?
Thanks.
You can overplot a second contour with a single, specific value for the contour, optionally specifying parameters like line width to make it obvious:
contour(x,y,z)
hold on
lev = z(n,m); % find the value you want in z
contour(x,y,z,lev,'Linewidth',2);

Multiple Marker Types for one Function

I am using the plot3c function to map a matrix of data in the x,y,z, and color axes. For clarification, my z-data and color data are one and the same, but represented on the two axes. Due to instrumental limitations, my data has a set of false color values where an unreadable point is represented with a 0. I would like to have every z/color value of 0 represented with a different marker type than the rest of the data. I know how to change marker type for a plot but I do not know how to set a marker type for specific values within a plot. How can I do this?
You could just overlay a second plot that only plots where z is 0:
% Your original plot, I'm assuming plot3c(x,y,z,z)
hold on
mask = z==0;
plot3(x(mask), y(mask), z(mask), '^')
Or more efficiently as suggested in radarhead's comment:
mask = z==0;
plot3c(x(~mask), y(~mask), z(~mask), z(~mask))
hold on
plot3(x(mask), y(mask), z(mask), '^')

Using different colors in Matlab

In a 3D scatter graph of MATLAB I have 15 different clusters of data that I want to highlight. I can see MATLAB has 8 specific colors. Is there any other way I could use 7 more colors just to distinguish the clusters?
Thanks
I would recommend to use this File Exchange submission - Generate maximally perceptually-distinct colors
It allows you to create a colormap with very distinguished colors and apply them with COLORMAP function. See help for this submission for more options.
colors = distinguishable_colors(n_colors);
For 3D scatter you can use this colors as an argument (C) in SCATTER3:
scatter3(X,Y,Z,[],colors)
To use this colors for different lines set them as default color order either for current figure:
set(gcf,'DefaultAxesColorOrder',colors)
or all figures:
set(0,'DefaultAxesColorOrder',colors
You can use the color property using set. You must first get a handle h to the drawing objects and set(h,'color',[0.2 0.3 0.9]). The color is rgb ranging from 0 to 1 for each channel.
From the Matlab documentation:
scatter(X,Y,S,C) displays colored circles at the locations specified
by the vectors X and Y (which must be the same size).
S determines the area of each marker (specified in points^2). S can be
a vector the same length as X and Y or a scalar. If S is a scalar,
MATLAB draws all the markers the same size. If S is empty, the default
size is used.
C determines the color of each marker. When C is a vector the same
length as X and Y, the values in C are linearly mapped to the colors
in the current colormap. When C is a 1-by-3 matrix, it specifies the
colors of the markers as RGB values. If you have 3 points in the
scatter plot and wish to have the colors be indices into the colormap,
C should be a 3-by-1 matrix. C can also be a color string (see
ColorSpec for a list of color string specifiers).
So, for example, say that your clusters are given by the columns of the matrices X and Y, with the k'th column being the k'th cluster, X being the X coordinates, and Y being the Y coordinates. We can do what you want as follows:
% make some random data in clusters:
n = 15;
m = 42;
X = 0.2*rand(m,n) + repmat(rand(1,n),m,1);
Y = 0.2*rand(m,n) + repmat(rand(1,n),m,1);
% lets change the colour map:
colormap(jet);
% now plot each, one at a time, and each with a different colour:
hold on;
for k=1:n
scatter(X(:,k),Y(:,k),40,k/n*ones(m,1));
end
If you don't like these colours, you can change the colormap, and if you don't like the color maps, you can, as the other answer points out, insert any RGB values you want.