How to create a color gradient using a third variable in Matlab? [duplicate] - matlab

This question already has answers here:
Change color of 2D plot line depending on 3rd value
(5 answers)
Closed 5 years ago.
How do you create a color gradient in Matlab such that you plot a 2D line plot of y=y(x), and you color it using another variable that also depends on x such that z=z(x). A scatter or point plot is also fine by me.
I would also like to have a colormap legend kind of thing showing the color gradient and it's actual representation of z. This stuff is quite common in visualisation tools such as VisIt and ParaView but I could not yet FIGURE it out in Matlab.

If a scatter plot is fine, you can use the 4th input to scatter:
x = -10:0.01:10;
y = sinc(x);
z = sin(x);
scatter(x,y,[],z,'fill')
where z is the color.

The only way I know of to do this is with a little trick using surf:
% Create some sample data:
x = cumsum(rand(1,20)); % X data
y = cumsum(rand(1,20)); % Y data
z = 1:20; % "Color" data
% Plot data:
surf([x(:) x(:)], [y(:) y(:)], [z(:) z(:)], ... % Reshape and replicate data
'FaceColor', 'none', ... % Don't bother filling faces with color
'EdgeColor', 'interp', ... % Use interpolated color for edges
'LineWidth', 2); % Make a thicker line
view(2); % Default 2-D view
colorbar; % Add a colorbar
And the plot:

To manipulate the color of the line continuously, you'll want to use surface.
While at first look, this function looks most useful for plotting 3d surfaces, it provides more flexibility for line coloring than the basic plot function. We can use the edges of the mesh to plot our line, and take advantage of the vertex colors, C, to render interpolated color along the edge.
You can check out the full list of rendering properties, but the ones you are most likely to want are
'FaceColor', 'none', do not draw the faces
'EdgeColor', 'interp', interpolate between vertices
Here's an example adapted from MATLAB Answers post
x = 0:.05:2*pi;
y = sin(x);
z = zeros(size(x)); % We don't need a z-coordinate since we are plotting a 2d function
C = cos(x); % This is the color, vary with x in this case.
surface([x;x],[y;y],[z;z],[C;C],...
'FaceColor','none',...
'EdgeColor','interp');

Generate a colormap, e.g. jet(10). The example would generate a 10*3 matrix.
Use interp1 to interpolate between the values in the RGB space using your data by setting the first color as the lowest value and the last color as the highest value. This would generate a n*3 matrix where n is the number of data points.
Use scatter with the optional parameter c to plot the points with the interpolated colors.
activate colorbar to show the colorbar.

Related

Matlab how to make smooth contour plot?

I want to represent data with 2 variables in 2D format. The value is represented by color and the 2 variables as the 2 axis. I am using the contourf function to plot my data:
clc; clear;
load('dataM.mat')
cMap=jet(256); %set the colomap using the "jet" scale
F2=figure(1);
[c,h]=contourf(xrow,ycol,BDmatrix,50);
set(h, 'edgecolor','none');
xlim([0.0352 0.3872]);
ylim([0.0352 0.3872]);
colormap(cMap);
cb=colorbar;
caxis([0.7 0.96]);
% box on;
hold on;
Both xrow and ycol are 6x6 matrices representing the coordinates. BDmatrix is the 6x6 matrix representing the corresponding data. However, what I get is this:
The following is the xrow and yrow matices:
The following is the BDmatrix matices:
Would it be possible for the contour color to vary smoothly rather than appearing as straight lines joining the data points? The problem of this figure is the coarse-granularity which is not appealing. I have tried to replace contourf with imagec but it seems not working. I am using MATLAB R2015b.
You can interpolate your data.
newpoints = 100;
[xq,yq] = meshgrid(...
linspace(min(min(xrow,[],2)),max(max(xrow,[],2)),newpoints ),...
linspace(min(min(ycol,[],1)),max(max(ycol,[],1)),newpoints )...
);
BDmatrixq = interp2(xrow,ycol,BDmatrix,xq,yq,'cubic');
[c,h]=contourf(xq,yq,BDmatrixq);
Choose the "smoothness" of the new plot via the parameter newpoints.
To reduce the Color edges, you can increase the number of value-steps. By default this is 10. The following code increases the number of value-steps to 50:
[c,h]=contourf(xq,yq,BDmatrixq,50);
A 3D-surf plot would be more suitable for very smooth color-shading. Just rotate it to a top-down view. The surf plot is also much faster than the contour plot with a lot of value-steps.
f = figure;
ax = axes('Parent',f);
h = surf(xq,yq,BDmatrixq,'Parent',ax);
set(h, 'edgecolor','none');
view(ax,[0,90]);
colormap(Jet);
colorbar;
Note 1: Cubic interpolation is not shape-preserving. That means, the interpolated shape can have maxima which are greater than the maximum values of the original BDmatrix (and minima which are less). If BDmatrix has noisy values, the interpolation might be bad.
Note 2: If you generated xrow and yrow by yourself (and know the limits), than you do not need that min-max-extraction what I did.
Note 3: After adding screenshots of your data matrices to your original posting, one can see, that xrow and ycol come from an ndgrid generator. So we also must use this here in order to be consistent. Since interp2 needs meshgrid we have to switch to griddedInterpolant:
[xq,yq] = ndgrid(...
linspace(min(min(xrow,[],1)),max(max(xrow,[],1)),newpoints ),...
linspace(min(min(ycol,[],2)),max(max(ycol,[],2)),newpoints )...
);
F = griddedInterpolant(xrow,ycol,BDmatrix,'cubic');
BDmatrixq = F(xq,yq);

Color-coded representation of data in a 2-D plot (in MATLAB)

I have several 4 x 4 matrices with data that I would like to represent in a 2-D plot. The plot is supposed to show how the results of a simulation change with varying parameters.
On the y-axis I would like to have the possible values of parameter A (in this case, [10,20,30,40]) and on the x-axis I want to have the possible values of parameter B (in this case, [2,3,4,5]). C is a 4 x 4 matrix with the evaluation value for running the simulation with the corresponding parameter combination.
Example: The evaluation value for the parameter combination A = 10, B = 2 equals 12 dB. I would like to plot it at the cross section A and B (I hope you understand what I mean by this) and code the value by a fat colored dot (e.g. red means high values, blue means low values).
How can I do this? I would basically like to have something like mesh without lines.
I'm sorry for my imperfect English! I hope you understood what I would like to achieve, thank you in advance!
You can do this with the mesh command (and the built-in colormaps you can choose from can be found here, or you could even make your own):
[A, B] = meshgrid(10:10:40, 2:5); % Grids of parameter values
C = rand(4); % Random sample data
hMesh = mesh(A, B, C); % Plot a mesh
set(hMesh, 'Marker', '.', ... % Circular marker
'MarkerSize', 60, ... % Make marker bigger
'FaceColor', 'none', ... % Don't color the faces
'LineStyle', 'none'); % Don't render lines
colormap(jet); % Change the color map
view(0, 90); % Change the view to look from above
axis([5 45 1.5 5.5]); % Expand the axes limits a bit
colorbar; % Add colorbar
And here's the plot:

Color coded 2D plot in MATLAB

I have a d1×d2 array A of integer values and want to color code display them on the xy-plane in a rectangle scaled to d1×d2 using colors that match the magnitude of the value of array at that location. I also want to display the color chart which indicates which color is which magnitude as in the following figure:-
Is there a simple code that can do this?
Or is this kind of charting need special packages?
Will this work ('A' is matrix with non-negative entries)?
function plot2Ddistprf(A, Length, Breadth)
Amax=max(A(:));
A=A/Amax;
G1 = linspace(0,Length,size(A,1));
G2 = linspace(0,Breadth,size(A,2));
[X,Y] = meshgrid(G1,G2);
% plot data
figure; % create a new figure
contourf(X,Y,A); % plot data as surface
caxis([1,100]); % set limits of colormap
colorbar; % display the colorbar
No external library or special package is needed to create such a plot. You can use contourf to plot the data. Then, set the colormap to gray. With caxis you can control the range of colors. colorbar shows the bar on the right side.
The result looks like this:
Here is the code:
% generate sample data
d1 = linspace(-3,3,200);
d2 = linspace(-3,3,200);
[X,Y] = meshgrid(d1,d2);
A = -abs(peaks(X,Y))+100;
% plot data
figure; % create a new figure
contourf(X,Y,A); % plot data as surface
colormap(gray); % use gray colormap
caxis([91,100]); % set limits of colormap
colorbar; % display the colorbar
title('The Title');
xlabel('y');
ylabel('x');
Try the contourf function and then add the colorbar
contourf(A)
colorbar

Surface plot with highligheted cut

I would like to plot a 3D surface using the Matlab surf function. The whole surface should be in gray scale, then I need to highlight a specific cut of the surface using a different color.
I thought this code would've worked but it doesn't.
Mat = randi(100); % Matrix to be plotted in gray scale
ind_highlight = 10; % Row of the matrix to be highlighted
Mat2 = Mat;
Mat2([1:ind_highlight-1, ind_highlight+1:end] ,:) = NaN;
figure
surf(X,Y,Mat)
colormap gray
hold on
% Highlight the ind_highlight row
surf(X,Y,Mat2)
colormap hsv
Any help would be highly appreciated!
It seems there is no way to use different colormap to obtain the desired effect since the colormap "belongs" to the figure.
I've found a possible solution which does not use colormap.
It is based on the specifying the color matrix in the call to surf, one for the whole matrix, one for the section to be highlighted, then superimposing the second one to the first one.
Unfortunately, I've not been able to set the first ad gray.
I've used the peaks matrix instead of your "randi" in order to have a more smooth surface to work with and inserted the script in a for loop to highlight different section of the matrix
% Mat = randi(100,100,100); % Matrix to be plotted in gray scale
% Alternative definition of the Matrix to be displayed
n_pt=50;
Mat=peaks(n_pt);
% Generate meshgrid
x=1:n_pt;
y=1:n_pt;
[X,Y]=meshgrid(x,y);
ind_highlight_2 = 5; % Number of rows of the matrix to be highlighted
% Generate two set of color matrix
% The first on for the whole surf
% The second one for the section to be highlighted
a=randi(2,n_pt,n_pt);
b=randi(10,n_pt,n_pt);
for i=1:n_pt-ind_highlight_2
ind_highlight_1 = i; % Starting row of the matrix to be highlighted
Mat2 = Mat;
% Modified set of data (in the original just one row was left
% Mat2([1:ind_highlight-1, ind_highlight+1:end] ,:) = NaN
Mat2(ind_highlight_1:ind_highlight_1+ind_highlight_2,:) = NaN;
COL=a;
COL(ind_highlight_1:ind_highlight_1+ind_highlight_2,:)=b(ind_highlight_1:ind_highlight_1+ind_highlight_2,:);
% Plot the surf specifying the color
s_h=surf(X,Y,Mat,COL);
shading interp
% view([0 90])
% f_name=['jpg_name_' num2str(i)]
% print('-djpeg75',f_name)
pause(.1);
end
Hope this helps.

Matlab: How to smooth colors of matrix in plot3( ) function?

I am using plot3 to plot a matrix such that the resultant figure shows different colors for each vector of that matrix:
plot3(Grid.x1(:,:),Grid.x2(:,:),phi(:,:))
How can I smooth the coloring of this plot? Thanks!
You can use varycolor from FileExchange to construct and control a continuous range color spectrum. This way the transition between different lines will seem more natural and proximal lines will have similar colors.
You can read more and see examples usage here http://blogs.mathworks.com/pick/2008/08/15/colors-for-your-multi-line-plots/
Example:
[X,Y,Z] = peaks(128);
% raw plot3()
figure; plot3(X, Y, Z);
% define set equal to line number
ColorSet = varycolor(128);
% smooth plot3()
figure; hold all;
set(gca, 'ColorOrder', ColorSet);
plot3(X, Y, Z); view(3);
Update:
For a continuous 3D plot (i.e. a surface) you can use surfl instead of plot3 and display your data as a 3-D Surface Plot (with Shading). You can additionally apply any colormap on the resulting surface, i.e. gray or ColorSet as above.
surfl(X,Y,Z);
shading interp;
colormap(gray);