Create a correlation graph in Matlab - matlab

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.

Related

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

Xtick marks and Xtick labels on heatmap in Matlab

Environment: Windows 7 64 bit, Matlab 2014a
Objective:
To draw a heatmap of errors for two parameters to be optimized.
To put proper tick marks and tick values
Draw the grid lines in the correct place
Problem: Arranging the X and Y tick positions and values. When the last ("end") value of the vectors in x and y axes are the same, the code I use puts the ticks and values properly. However, when the end values are different it does not, and produces something really weird.
Below I have included the code which I have modified so that you can run it without the need of adding anything. Of course in my case the error vector are the error values, not random numbers. To see the problem of "end value" use the second b vector.
fontsize = 20
k = [2^-5, 2^-3, 2^-1, 2^0, 2^1, 2^3, 2^5, 2^7, 2^9, 2^11, 2^13, 2^15]
b = [2^-5, 2^-3, 2^-1, 2^0, 2^1, 2^3, 2^5, 2^7, 2^8, 2^9, 2^10, 2^11, 2^13, 2^15]
% b = [2^-5, 2^-3, 2^-1, 2^0, 2^1, 2^3, 2^5, 2^7, 2^8, 2^9, 2^10, 2^11, 2^13, 2^19]
errorVector = randi(20, 1, length(b)*length(k))'
figure
% Create a matrix from error vector (size of error vector is [length(k)*length(b),1])
B = reshape(errorVector, [length(b), length(k)])
B = flipud(B)
% imagesc(x,y,C)
imagesc(b, k, B)
title('Heatmap Parameters Percent Error', 'FontSize', fontsize);
% Set colorbar limits
caxis([0 15])
colorbar;
ax1 = gca;
xTickLabel = (k)'
xTick = linspace(k(1), k(end), numel(xTickLabel))';
set(ax1, 'XTick', xTick, 'XTickLabel', xTickLabel)
xlabel('k parameter', 'FontSize', fontsize)
yTickLabel = (b)'
yTick = linspace(b(1), b(end), numel(yTickLabel))';
set(ax1, 'YTick', yTick, 'YTickLabel', flipud(yTickLabel(:)))
ylabel('b parameter', 'FontSize', fontsize)
set(ax1,'FontSize', fontsize)
Here, change any of the end values of b or k vectors, and the program will output a graph where the X and Y ticks are totally wrong.
Also, I would like to draw grid lines. When I use "grid on" it draws grid lines right on the tick marks which is not correct in the case of heatmap. Because tick marks will be in the center of the columns -or rows- but the grid lines should be at the boundaries between the columns -or rows.
By the way if you know a better way to plot a heatmap in Matlab, please do tell.
Please help me solve this problem. Any help is appreciated,
Ilyas
First of all - you don't need to flipud the B matrix - by default imagesc plots the y-data inversed, but you can fix this with the following statement:
set(gca,'ydir','normal');
This also means you don't have to mess around with flipping the tick-labels. You can get the labels right by doing the following:
% replace the imagesc call with:
imagesc(B);
set(gca,'ydir','normal');
% formatting stuff
...
% replace the set commands with:
set(ax1, 'XTick', 1:length(k), 'XTickLabel', k)
set(ax1, 'YTick', 1:length(b), 'YTickLabel', b)
By default, if you don't provide x and y data to the imagesc command, it will number them linearly (1,2,3...). Basically what we've done here is make sure that it has ticks for each of the elements of b and k, and then set the labels to the values of the respective vectors.
Unfortunately, I'm not sure if there is a way to get the grid spacing right with imagesc or not. You could try using pcolor instead, which has it's own set of issues, but allows you to get grid lines (of sorts) between the elements. It also allows you to use an interpolated shading mode, which will make your plot look more like a typical heat map.
To use pcolor instead, you just have to replace imagesc:
% imagesc(B);
% set(gca,'ydir','normal');
pcolor(B);
% this uses a smoother shading method, for a more 'heatmap' like output
% shading interp
Everything else should work as intended, I believe.

Set the position of the Xtick labels matlab

I want to shift the x ticks labels downwards in this figure:
I'm not sure how to do this?
This is the script I'm using:
y=[0.5093 0.8526 0.9171];
x=[0 1600 1100];
hand =plot(y, 'ob-');
set(gca, 'XTick',1:3, 'XTickLabel',{'no interference' '1600' '1100'})
set(hand, 'LineWidth', 4);
set(hand, 'MarkerSize', 30);
set(findobj('type','text'),'FontSize',25);
set(gca,'FontSize',25);
set(findobj('type','axes'),'FontSize',25);
h=get(gca,'Title');
set(h,'FontSize',20);
Following the example from this mathworks solution, you can use the text function to add labels in any position you wish.
Increase the value of delta for a larger gap between x tick labels and x axis.
EDIT: Added custom control of yticks: the value of stp changes the step between each tick. Obviously a more general solution would identify the end-points of the tick range automatically as well.
figure(1), clf
% set data as your example
y=[0.5093 0.8526 0.9171];
x=[0 1600 1100];
Xt=1:length(x);
hand =plot(y, 'ob-');
set(gca, 'XTick',Xt);
stp=0.05;
Yt=0.5:stp:0.95;
set(gca, 'ytick', Yt)
% Reduce the size of the axis so that all the labels fit in the figure.
pos = get(gca,'Position');
set(gca,'Position',[pos(1), .2, pos(3) .7])
ax = axis; % Current axis limits
axis(axis); % Set the axis limit modes (e.g. XLimMode) to manual
Yl = ax(3:4); % Y-axis limits
Xl = ax(1:2);
% Place the text labels -- the value of delta modifies how far the labels
% are from the axis.
delta=0.1;
t = text(Xt, Yl(1)*ones(1,length(x))-delta, {'no interference' '1600' '1100'});
%set(t, 'HorizontalAlignment','left','VerticalAlignment','top')
set(t, 'HorizontalAlignment','center','VerticalAlignment','middle')
% Remove the default labels
set(gca,'XTickLabel','')
% and continue with your other settings as required
set(hand, 'LineWidth', 4);
set(hand, 'MarkerSize', 30);
set(findobj('type','text'),'FontSize',25);
set(gca,'FontSize',25);
set(findobj('type','axes'),'FontSize',25);
h=get(gca,'Title');
set(h,'FontSize',20);
The text function has lots of options that you can configure.
I think what most people want is something that works in 2-3 lines of code, nevermind-ing a quick&dirty approach.
This is undocumented (credits go to here) but just works:
% adjust ticklabels away from axes
a=gca;
a.XRuler.TickLabelGapOffset = 8;
a.YRuler.TickLabelGapOffset = 8;
tested with Matlab 2019a

How to set colorbar labels

I have some points in a 'jet' colormap. The points have a coefficient that can go from 0 to 1, but usually they dont cover all the range, e.g 0.75-0.9.
When I plot those points I colour them so 0.75 is the lesser colour in the colormap and 0.9 is the maximum color in the colormap, so all the colormap is shown. What I want to do is show that in the colorbar also. When I plot the colorbar the labels on it go to 64, but I want them from 0.75 to 0.9. How can I do that?
EDIT
I don't think the code itself helps a lot but here it goes, just in case. In the colors variable I convert the ZNCC to the range of the colormap.
EDIT2
I found the reason why caxis is not working for me. Here is the code:
%this is why it doesnt work
im=imread('someimageyouwanttotest_inRGB.png')
imshow(im)
points=[1, 2;1 , 2 ;0.3,0.7]
ZNCC=points(3,:)
cmap=colormap('jet');
colors=cmap(round( ((1-min(ZNCC))+ZNCC-1).*(size(cmap,1)-1)/max((1-min(ZNCC))+ZNCC-1))+1,: );
hold on
for i=1:length(ZNCC)
plot(points(1,i),points(2,i),'.','Color',colors(i,:));
end
colorbar()
hold off
I think that is your code displays all your colours correctly then rather just set up the colour bar first on no image:
points=[1, 2;1 , 2 ;0.3,0.7]
ZNCC=points(3,:)
cmap=colormap('jet');
caxis([min(ZNCC) max(ZNCC)]);
colorbar();
hold on
%this is why it doesnt work
im=imread('someimageyouwanttotest_inRGB.png')
imshow(im)
colors=cmap(round( ((1-min(ZNCC))+ZNCC-1).*(size(cmap,1)-1)/max((1-min(ZNCC))+ZNCC-1))+1,: );
for i=1:length(ZNCC)
plot(points(1,i),points(2,i),'.','Color',colors(i,:));
end
hold off
I can't test it as I don't have imshow :/
If caxis is not working for you, you could store the return from colorbar - it is a handle to the colorbar object. Then you can set its properties, like 'YTick' and 'YLim'. The full list of properties you can set is the same as the Axes Properties (because the colorbar is just an axes object, after all).
Here is an example:
% Generate some random data
z = rand(10);
[x, y] = meshgrid(1:size(z, 1));
% Plot colour map
pcolor(x, y, z);
shading interp; % Comment out to disable colour interpolation
colormap jet;
% Setup colorbar
c = colorbar();
set(c, 'YTick', [0.75 0.875 1]); % In this example, just use three ticks for illustation
ylim(c, [0.75 1]);
It is only necessary to do this once, after you've finished plotting.
Edit: If you need the limits and ticks automatically from the data, then you can do something like
% Find the limits
lims = [min(z(:)) max(z(:))];
% Function for rounding to specified decimal places
dprnd = #(x, dps)round(x*(10.^dps))./(10.^dps);
% Generate ticks
nTicks = 5;
nDps = 2;
ticks = dprnd(linspace(lims(1), lims(2), nTicks), nDps);
set(c, 'YTick', ticks);

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