Subplot with axis square - matlab

I am trying to use subplot with square axis but I failed, Below part of my code. I got Fig that has two plots but each one has different size
for i=1:N
figure
subplot (2,1,1);
plot (r(i,:),p(i,:));
grid on
set(gca, 'XTick', 0:0.5:4)
set(gca, 'YTick', -1:0.15:0.2)
axis square
xlim([0 4]);
ylim([-1 0.2]);
subplot (2,1,2);
[r,y]= meshgrid(linspace(0,4),linspace(0,4));
U =eval(U1);
[~,h] = contour(r,y,U,[0.001 0.01 0.05 0.08 0.1 0.2 0.25 0.3 0.4]);
set(h,'ShowText','on','TextStep',get(h,'LevelStep')*2)
colormap cool
grid on
axis square
hold on
xlim([0 4]);
ylim([0 4]);
plot (R,Y,'*r');
hold off
daspect([1 1 1]);
end

You should call axis square after changing the x and y limits of the axes after all plotting is done. If you change the xlims and ylims after calling axis square MATLAB will forget that you wanted it to be square. This is because there is no property of the axes that indicates that you want a square matrix, it's simply computed when you call axes square based upon the current xlims and ylims and the data aspect ratio.
subplot (2,1,1);
plot (r(i,:),p(i,:));
grid on
set(gca, 'XTick', 0:0.5:4)
set(gca, 'YTick', -1:0.15:0.2)
%// Do not call axis square here
xlim([0 4]);
ylim([-1 0.2]);
%// Call axis square here after you change the x/y limits
axis square

Related

Tight subplot with colorbars and subplot's 3rd parameter in Matlab?

I would like to have a tight subplot i.e. minimum spacing between figures in the subplot where
you have subplot's 3rd parameter i.e. you can decide where the picture is going to be i.e. easy to move between subplot and new_tight_subplot, and
you can use it with colorbars.
I have profiled the most popular tight subplots in FileExchange of Matlab.
None (etc most popular here Pekka's version) can pass the following code
data=randi(513,513);
ax1=subplot(2,1,1);
plot(mat2gray(pdist(data, 'correlation')));
cbar1=colorbar(ax1);
axis(ax1, 'square');
xlim([0 size(mat2gray(pdist(data, 'correlation')),2)]);
set(cbar1, 'Visible', 'off')
ax2=subplot(2,1,2);
imshow(squareform( mat2gray(pdist(data, 'correlation')), 'tomatrix') );
colormap('parula'); colorbar;
axis(ax2, 'square');
Pekka's tight_subplot requires the syntax without the third parameter.
It also fails with colorbars as in the example. I do not understand why.
Hypothesis about the 2nd problem with colorbars
I think the problem can be the fact that colorbar objects are children of the figure, not axis, and their position is defined in normalized figure units; like for annotated objects as discussed here.
However, I am unsure how to adjust the tight subplot for this.
Test output after Author's edit in tight_subplot in FileExchange 3.3.2016
Code
data = randi(513, 513);
ax1=tight_subplot(2,1,[.01 .03],[.1 .01],[.01 .01]);
plot(mat2gray(pdist(data, 'correlation')));
ax2=tight_subplot(2,1,[.01 .03],[.1 .01],[.01 .01]);
imshow(squareform( mat2gray(pdist(data, 'correlation')), 'tomatrix') );
You get
where the plot fails and there is noisy part in the second figure for some reason. Why?
Extension of Suever's answer to 2x2 figures
ax1=axes('OuterPosition', [0 0.5 0.5 0.5]);
plot(u, 'Parent', ax1);
set(ax1, 'XLim', [0, size(u,1)]);
cbar1 = colorbar(); % not needed to assign ax1
set(cbar1, 'Visible', 'off')
ax3 = axes('OuterPosition', [0 0 0.5 0.5]);
image(data, 'Parent', ax3);
D=mat2gray(pdist(pTFD, 'correlation'));
ax2 = axes('OuterPosition', [0.51 0.5 0.5 0.5]);
plot(D, 'Parent', ax2);
set(ax2, 'XLim', [0, size(D,1)])
axis(ax2, 'square');
xlim([0 size(D,2)]);
set(cbar2, 'Visible', 'off')
ax4 = axes('OuterPosition', [0.51 0 0.5 0.5]);
imshow( D_square );
axis(ax4, 'square');
where 2x2 figure system and where I think equivalent
xlim([0 size(D,2)]); is same as set(ax1, 'XLim', [0, size(D,2)]);. Right?
...
How can you use Matlab's tight subplot with colorbars and third parameter?
The third parameter of tight_subplot defines the gaps between axis objects. For the built-in subplot command, the third parameter defines which axis is set as the CurrentAxes of the Figure. This option is not available in tight_subplot because I personally did not find it useful. Typically, I use the returned axes handles to specify where to add graphics.
Existing axes objects are repositioned when you add a colorbar.
I have added a second output argument to tight_subplot which provides the output position of the axes so that you can "reset" the axes positions after adding a colorbar.
[hax, position] = tight_subplot();
% Add a colorbar which alters the positions
colorbar();
% Now reset the positions back to where they were
set(hax, {'Position'}, pos);
Rather than trying to deal with subplot and different versions on the file exchange, I would probably just manually set the positions of my axes objects to get the effect that you want. You can use normalized units so that the positions scale as the size of the parent figure changes.
Also, you can set the OuterPosition property of the axes which takes into account the room needed to properly display all text labels of the axes.
figure
data=randi(513,513);
set(0, 'defaultaxeslooseinset', [0 0 0 0])
D = mat2gray(pdist(data, 'correlation'));
square = squareform(D, 'tomatrix');
% Set normalized outer position (x,y,width,height)
ax1 = axes('OuterPosition', [0, 0.5, 1, 0.5]);
plot(D, 'Parent', ax1);
set(ax1, 'XLim', [0, size(square, 1)])
axis(ax1, 'square');
cbar1 = colorbar();
set(cbar1, 'Visible', 'off')
% Set normalized outer position (x,y,width,height)
ax2 = axes('OuterPosition', [0 0 1 0.5]);
imshow(square);
colormap('parula'); colorbar;
axis(ax2, 'square');
And if you remove the x and y ticks on the axes
set([ax1,ax2], 'xtick', [], 'ytick', []);
This can easily be adapted to any dimensions with something similar to the following
figure;
% [Rows, Columns]
axdim = [3, 3];
width = 1 ./ axdim(2);
height = 1./ axdim(1);
[x,y] = meshgrid(linspace(0,1,axdim(2)+1), ...
linspace(0,1, axdim(1)+1));
for k = 1:numel(x)
ax = axes('OuterPosition', [x(k), y(k), width, height]);
set(ax, 'xtick', [], 'ytick', []);
end

No Gap Next to Axis Label in Matlab?

Matlab 2015b or Matlab 2016a.
I would like to have grid lines going across Subplot's spacing between the figures in order to evaluate better two pictures horizontally.
However, I have a small gap between the two figures at the lower right-hand-side corner because which is misaligning the figures
where the gap is because of the 10^4 at lower right-hand-side corner.
I would also like to have horizontal lines going across the spacing between the two figures, but I cannot do it before the gap problem is solved.
Code where the relative alignment is done as described in the answer here about the thread Tight subplot with colorbars and subplot's 3rd parameter in Matlab?
data=randi(513,513);
D=mat2gray(pdist(data, 'correlation'));
% Set normalized outer position (x,y,width,height)
ax1=axes('OuterPosition', [0 0.5 0.5 0.5]);
plot(D, 'Parent', ax1);
xlim([0 size(D,2)]);
set(cbar1, 'Visible', 'off')
title('Signal');
ax2=axes('OuterPosition', [0.51 0.5 0.5 0.5]);
plot(D, 'Parent', ax2);
set(ax2, 'XLim', [0, size(D,1)])
axis(ax2, 'square');
title('Corr pdist');
Output of Suever's answer
I tried unsuccessfully change two (2) in sprintf('%.2g', x) bigger and smaller
ax2 = axes('OuterPosition', [0.51 0.5 0.5 0.5]);
plot(D, 'Parent', ax2);
set(ax2, 'XLim', [0, size(D,1)])
axis(ax2, 'square');
title('Corr pdist');
cbar2 = colorbar(); % ax2 not needed here in brackets
set(ax2, 'XLim', [0 size(D,2)]);
set(cbar2, 'Visible', 'off')
grid minor;
% https://stackoverflow.com/a/35776785/54964
xticks = get(ax2, 'xtick');
labels = arrayfun(#(x)sprintf('%.2g', x), xticks, 'uniform', 0);
set(ax2, 'xticklabels', labels);
It gives
where those ticks are not XMinorTicks but simply ticks (wrongly marked in the picture).
They are zero points at some points in the x-axis. When x-axis gets larger, MATLAB automatically adds new xtick marks but without complete labels.
I think it would be better to have another symbol than zero there. How can you have some other mark than zero for incomplete labels of xticks?
How can you align the 10^4 next to the last number in the second figure?
I would get the current xtick locations, convert those to strings, and then set the xticklabels property of the axes.
xticks = get(ax2, 'xtick');
labels = arrayfun(#(x)sprintf('%.2g', x), xticks, 'uniform', 0);
set(ax2, 'xtick', xticks, 'xticklabels', labels);
If you want them to dynamically be computed as the figure changes size (and the xticks get recomputed) you can link this code to the SizeChangedFcn of the figure.
func = #(varargin)set(ax2,'xticklabels',arrayfun(#(x)sprintf('%.2g',x),get(ax2, 'xtick'),'uni',0));
set(gcf, 'SizeChangedFcn', func)

Matlab - No luck when using 'xtick' to change axis on graph

I have the following graph in Matlab:
I have tried using 'xTick' and 'yTick' to make the axis on each subplot the same, but it's not accomplishing what I would like it to. I also want the both axes of each subplot to share the same range so that I can easily compare the graphs. (i.e. ranging from 0 - 20, in y, and 0 - 400 in x).
I'm not sure how to change this.
My attempt is below. Does anyone know how to do this?
figure()
hold on
subplot (1,2,1);
% xlim([0 400]);
% ylim([0 25]);
graph_made = [num_calls_made];
plot (graph_made);
title('Number of calls made')
xlabel('ID Number of caller');
ylabel('Number of calls');
set(gca, 'XTick', [0:100:400]);
set(gca, 'YTick', [0:5:20]);
subplot (1,2,2);
graph_rec = [num_calls_received];
plot (graph_rec);
title('Number of calls received')
xlabel('ID Number of caller');
ylabel('Number of calls');
set(gca, 'XTick', [0:100:400]);
set(gca, 'YTick', [0:5:20]);
hold off
If you want the axes limits to stay linked as a user interactively zooms or pans, you can also use the linkaxes command...
subplot(1,2,1)
% your plotting code here...
ax = gca; %get the handle to the current axis
subplot(1,2,2)
% your plotting code here...
ax(end+1) = gca; %get the handle to the current axis
linkaxes(ax); %this will link both the x and y axes.
XTick and YTick only change where the labels on axes go, not the limits of the axes. To change those, you have to use axis (or xlim and ylim):
axis([0 400 0 20]) %// [xmin xmax ymin ymax]

axes labels not displaying on 3d subplots

I have created 5 3D subplots which include a for loop. However, the labels of the X and Y axes are not displaying for some reason. I would appreciate any help on this matter. Below is the code.
On a separate note, any suggestions to make the figure more aesthetically pleasing would also be much appreciated.
% parameters
b=0.5;
O=27;
x=1:1:5;
% energies
e1 = 1:1:100;
e2 = 1:1:100;
% function
[e1,e2]=meshgrid(e1,e2);
hb=#(x)((O.^2)./factorial(O-x)).*...
exp(-b.*O.*e2);
hu=#(x)(O.^x).*...
exp(-b.*O.*e1);
p=#(x)hb(x)./(hb(x)+hu(x));
f=figure('visible','on')
clf(f);
for i=x
subplot(2,3,i);
mesh(e1,e2,p(i))
title(['X = ',int2str(i)], 'FontSize',12);
% log all axes
set(gca, 'XScale', 'log');
set(gca, 'YScale', 'log');
set(gca, 'ZScale', 'log');
axis([1 100 1 100 10^-300 1])
axis square
grid off
set(gca,'FontSize',10)
xlabel('e1')
ylabel('e2')
zlabel('p_{H}')
end
The issue seems to be something internal to MATLAB with how it is setting the position of the x and y labels when a 3D surface plot is used. This doesn't happen with a basic plot3 plot. If you do a get(get(gca,'Xlabel','Position')), you see that the z coordinate of the label is set to infinity, which I would guess is the problem.
I've come up with a less than ideal workaround, but it seems to accomplish the task:
% parameters
b=0.5;
O=27;
x=1:1:5;
% energies
e1 = 1:1:100;
e2 = 1:1:100;
% function
[e1,e2]=meshgrid(e1,e2);
hb=#(x)((O.^2)./factorial(O-x)).*...
exp(-b.*O.*e2);
hu=#(x)(O.^x).*...
exp(-b.*O.*e1);
p=#(x)hb(x)./(hb(x)+hu(x));
f=figure('visible','on');
clf(f);
for i=x
subplot(2,3,i);
mesh(e1,e2,p(i))
title(['X = ',int2str(i)], 'FontSize',12);
% log all axes
set(gca, 'XScale', 'log');
set(gca, 'YScale', 'log');
set(gca, 'ZScale', 'log');
axis([1 100 1 100 10^-300 1])
axis square
grid off
set(gca,'FontSize',10)
xlabel('e1')
ylabel('e2')
zlabel('p_{H}')
set(get(gca,'xlabel'),'Units','Normalized','Position',[0.75 0 0])
set(get(gca,'ylabel'),'Units','Normalized','Position',[0 0.05 0])
end
You'll probably have to manipulate those position vectors to get the labels exactly where you'd like.
I would also submit a bug report and see what MathWorks says.

Multiple y plots on same logarithmic scale for the x-axis

I am trying to plot 3 curves using the semilogx matlab function and add a fourth line to an additional y axis on the right. All of them should be plotted on the same logarithmic scale for the x-axis. The following code indicates the derived error; the x-axis is incorrect. The figure has to have a single x-axis mode of ticks, the logarithm one. How could this be fixed?
Plus, how can I add a legend for these 4 curves?
close all, clc
figure, semilogx([1:100:1000],[rand(1,10)],'bo-'),
xlabel('xlabel'),ylabel('ylabel'), hold on;
semilogx([1:100:1000], [rand(1,10)], 'ro-'), hold on,
semilogx([1:100:1000], [rand(1,10)], 'ko-'), hold off
legend('1','2','3','Location','Best')
ax1 = gca;
ax2 = axes('YAxisLocation','right',...
'Color' , 'none',...
'YColor', 'm');
linkaxes([ax1 ax2 ], 'x')
x4 = [1:100:1000];
y4 = [rand(1,10)*2];
line(x4, y4, 'color', 'm', 'Marker','x','LineStyle',':', 'parent',ax1)
ylabel('y2')
You can use plotyy function to plot two of your lines, one on the right and one on the left. You can then hold on and plot the remaining lines using semilogx.
plotyy([1:100:1000], [rand(1,10)], [1:100:1000], [rand(1,10)]*2, #semilogx);
hold on;
semilogx([1:100:1000], [rand(1,10)], 'ro-');
semilogx([1:100:1000], [rand(1,10)], 'mo-');
hold off;
legend('Line1','Line2','Line3','Line4','Location','Northwest')