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
Related
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.
Suppose I have a function w from 2D coordinate space to 1D values, such that
w(a,b) := min(a,b)
I want to represent this function as an heat map in Matlab.
For example, I draw a square on the Cartesian plane with vertices (0,0), (0,1), (1,0), (0,0). Then I colour the region inside the square, by assigning the same colour to any two pairs of points (a,b) and (c,d) if w(a,b)=w(c,d).
Is my understanding of a heatmap correct? If so, how can I achieve this in Matlab?
You can achieve this with surf, which plots a surface which looks like a heatmap when viewed from above. See the commented code for details:
% Define axes points as [0,0.1,0.2,...,1]
ax = 0:0.1:1;
% Make grid of values corresponding to min(x,y)
xy = bsxfun(#min, ax, ax');
% Plot
surf(xy); % Plot surface
view(2); % Look from "above" onto x-y plane
set(gca, 'XTickLabel', ax) % Set x-axis labels
set(gca, 'YTickLabel', ax) % Set y-axis labels
colorbar; % Show colorbar as a legend
Output:
You can extend this by using a custom function if min was just an example.
ax = 0:0.1:1;
% Define function
w = #(a,b) a - exp(b)
% Use custom function inside bsxfun
xy = bsxfun(w, ax, ax');
surf(xy); % ... etc
See the docs for details: https://uk.mathworks.com/help/matlab/ref/bsxfun.html
Also see the docs for pcolor which creates a 2D colour plot so no perspective change is needed, and contourf which outlines regions not all squares.
I want to plot a confusion matrix in MATLAB. Here's my code;
data = rand(3, 3)
imagesc(data)
colormap(gray)
colorbar
When I run this, a confusion matrix with a color bar is shown. But usually, I have seen confusion matrix in MATLAB will give counts as well as probabilities. How can I get them? How can I change the class labels which will be shown as 1,2,3, etc.?
I want a matrix like this:
If you do not have the neural network toolbox, you can use plotConfMat. It gets you the following result.
I have also included an independent example below without the need for the function:
% sample data
confmat = magic(3);
labels = {'Dog', 'Cat', 'Horse'};
numlabels = size(confmat, 1); % number of labels
% calculate the percentage accuracies
confpercent = 100*confmat./repmat(sum(confmat, 1),numlabels,1);
% plotting the colors
imagesc(confpercent);
title('Confusion Matrix');
ylabel('Output Class'); xlabel('Target Class');
% set the colormap
colormap(flipud(gray));
% Create strings from the matrix values and remove spaces
textStrings = num2str([confpercent(:), confmat(:)], '%.1f%%\n%d\n');
textStrings = strtrim(cellstr(textStrings));
% Create x and y coordinates for the strings and plot them
[x,y] = meshgrid(1:numlabels);
hStrings = text(x(:),y(:),textStrings(:), ...
'HorizontalAlignment','center');
% Get the middle value of the color range
midValue = mean(get(gca,'CLim'));
% Choose white or black for the text color of the strings so
% they can be easily seen over the background color
textColors = repmat(confpercent(:) > midValue,1,3);
set(hStrings,{'Color'},num2cell(textColors,2));
% Setting the axis labels
set(gca,'XTick',1:numlabels,...
'XTickLabel',labels,...
'YTick',1:numlabels,...
'YTickLabel',labels,...
'TickLength',[0 0]);
If you have the neural network toolbox you can use the function plotconfusion. You can create a copy and edit it to customise it further, for example to print custom labels.
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.
I'm trying to emulate this graph:
If I have a correlation matrix how can I create an output like this?
If you have an n x n correlation matrix M, and a vector L of length n containing the label for each bin, you can use something like the following:
imagesc(M); % plot the matrix
set(gca, 'XTick', 1:n); % center x-axis ticks on bins
set(gca, 'YTick', 1:n); % center y-axis ticks on bins
set(gca, 'XTickLabel', L); % set x-axis labels
set(gca, 'YTickLabel', L); % set y-axis labels
title('Your Title Here', 'FontSize', 14); % set title
colormap('jet'); % set the colorscheme
colorbar on; % enable colorbar
Rotating x-axis labels is not trivial, but the MATLAB Central File Exchange contains some solutions.
Adding to #Thomas C. G.'s answer, I'd use:
imagesc(myMatrix);
colormap(jet);
colorbar;
% then to set the axis titles you'll have to use
% Please note the curly braces for the cell array
labelNames = {'USA','NASDAQ','Dow Jones'};
set(gca,'XTickLabel',labelNames); % gca gets the current axis
set(gca,'YTickLabel'labelNames); % gca gets the current axis
Unfortunately, AFAIK, making the text labels vertical as they are in your figure is a bit harder. Maybe somebody else has knowledge to the contrary.
To plot a matrix as an image you just need to call two functions:
image(myMatrix)
colormap(jet)
The colormap function defines the colour pattern used to render the image. The image you posted is using the "jet" colormap.
And to show the colour scale beside the image use the colorbar function.