align axes in one figure - matlab

I have a figure with two different axes.
I cannot manage to get the axes aligned and to make the second axis invisible... I tried a couple if things (see comments in the code), but they did not work
clearvars
close all
clc
[X1,Y1,Z1] = peaks(25);
[X2,Y2,Z2] = peaks(25);
idx = find(X2>0);
Z2(idx) = NaN;
figure
set(gcf, 'Position', [0 0 800 800])
%%title
title('')
%%Create two axes
ax1 = axes;
pcolor(X1,Y1, Z1); shading flat
view(2)
ax2 = axes;
pcolor(X2,Y2, Z2); shading flat
%%link them
linkaxes([ax1,ax2]) %<==it didn't work
%ax1.XLim=[-3 3]; %<==I also tried this
%ax2.XLim=[-3 3];
%ax1.YLim=[-3 3];
%ax2.YLim=[-3 3];
%%Hide top axes
ax2.Visible = 'off'; %<== I thought that this would work
ax2.XTick = [];
ax2.YTick = [];
%%Colormaps
colormap(ax1, bone)
colormap(ax2, jet(26))
%%Add colorbars
set([ax1,ax2],'Position',[.17 .11 .685 .815]);
cb1 = colorbar(ax1,'position',[.08 .11 .03 .815]);
set(get(cb1,'ylabel'),'String','whatever','interpreter','latex', 'fontsize',20);
cb2 = colorbar(ax2,'position',[.92 .11 .03 .815]);
set(get(cb2,'ylabel'),'String','whatever','interpreter','latex', 'fontsize',20);
caxis(ax1,[-7 7])
caxis(ax2,[-5 5])
xlabel(ax1,'stuff')
ylabel(ax1,'other stuff')
Note: I am using 2017a

I really have no idea whether your approach is correct or not since I never attempted to produce a similar plot before. What I know is that when a figure is created, it already includes a default axis. Thus, calling the function axes() twice inserts two supplementar axes in the figure... and this is the proof:
Neither ax1 nor ax2 are the cause of this problem. The mismatching axis is the third one, the default one that was created together with the figure instance. What's happening in between is kinda weird (I spent some time trying to debug everything properly, but it's still not clear how instances are being handled)... anyway I found a workaround for deleting it:
clc();
clearvars();
close all;
[X1,Y1,Z1] = peaks(25);
[X2,Y2,Z2] = peaks(25);
idx = find(X2 > 0);
Z2(idx) = NaN;
f = figure();
set(gcf,'Position',[0 0 800 800])
title('');
ax1 = axes();
pcolor(X1,Y1,Z1);
shading flat;
xlabel(ax1,'stuff')
ylabel(ax1,'other stuff')
view(2);
ax2 = axes();
pcolor(X2,Y2,Z2);
shading flat;
ax2.Visible = 'off';
colormap(ax1,bone());
colormap(ax2,jet(26));
set([ax1,ax2],'Position',[.17 .11 .685 .815]);
cb1 = colorbar(ax1,'position',[.08 .11 .03 .815]);
set(get(cb1,'ylabel'),'String','whatever','interpreter','latex', 'fontsize',20);
cb2 = colorbar(ax2,'position',[.92 .11 .03 .815]);
set(get(cb2,'ylabel'),'String','whatever','interpreter','latex', 'fontsize',20);
caxis(ax1,[-7 7]);
caxis(ax2,[-5 5]);
set(ax1,'Tag','keep');
set(ax2,'Tag','keep');
delete(findall(f,'Type','Axes','-not','Tag','keep'));
Since the axes you create are referenced into a variable, once the plotting has been performed you assign the same Tag property to both. Then, using the findall function on the figure handle, you find the third axis (which is the one without the predefined Tag) and you delete it. Result:
EDIT
After further investigations, the followin code can be used instead for producing a cleaner version of this plotting:
clc();
clearvars();
close all;
[X1,Y1,Z1] = peaks(25);
[X2,Y2,Z2] = peaks(25);
idx = find(X2 > 0);
Z2(idx) = NaN;
f = figure();
set(gcf,'Position',[0 0 800 800])
ax1 = axes();
pcolor(X1,Y1,Z1);
shading flat;
xlabel(ax1,'stuff')
ylabel(ax1,'other stuff')
view(2);
ax2 = axes();
pcolor(X2,Y2,Z2);
shading flat;
ax2.Visible = 'off';
colormap(ax1,bone());
colormap(ax2,jet(26));
set([ax1,ax2],'Position',[.17 .11 .685 .815]);
cb1 = colorbar(ax1,'position',[.08 .11 .03 .815]);
set(get(cb1,'ylabel'),'String','whatever','interpreter','latex', 'fontsize',20);
cb2 = colorbar(ax2,'position',[.92 .11 .03 .815]);
set(get(cb2,'ylabel'),'String','whatever','interpreter','latex', 'fontsize',20);
caxis(ax1,[-7 7]);
caxis(ax2,[-5 5]);

Related

Matlab subplot linkaxes is not lining up the axes as expected

I can't seem to get linkaxes to work (code is below). I am trying to get the subplots to line up, such that visually the x-axis is has the same range and width for both subplots. The misalignment is in both the pop-up figure window and the saved JPG. Using Matlab R2018a.
Here is my code, and below is what the figure looks like:
x1 = [27247 26973 27265 28924 27182 27430 26534 26839 7876 26484 29787 26934 27218 25777 27801 8250 34820 7980 26927 34639];
y1 = [-2350 -3334 -2948 -2336 -2778 -2813 -3383 -3635 -31 -3334 -4216 -3284 -2271 -2477 -2058 375 -821 351 -3441 -1108];
ax1 = subplot(2,1,1);
scatter(x1, y1)
box on
grid on
axis equal
xlims = get(gca, 'XLim')
ax = gca;
ax.XRuler.Exponent = 0;
ax.YRuler.Exponent = 0;
xlims = get(gca, 'XLim')
ax2 = subplot(2,1,2);
scatter(x1, y1)
xlim(xlims)
box on
grid on
ax = gca;
ax.XRuler.Exponent = 0;
linkaxes([ax1,ax2],'x')
I've also tried this (below), but it doesn't change the plot.
% adding this to the first subplot:
xlims = get(gca, 'XLim')
positioning = get(gca,'position');
% adding this to the second subplot:
xlim(xlims)
set(gca, 'position', [positioning(1) positioning(2)/5 positioning(3) positioning(4)]) %x y width height
And here is what the figure looks like:
This was solved on the Matlab forums, and here is a summary/application of the solution:
x1 = [27247 26973 27265 28924 27182 27430 26534 26839 7876 26484 29787 26934 27218 25777 27801 8250 34820 7980 26927 34639];
y1 = [-2350 -3334 -2948 -2336 -2778 -2813 -3383 -3635 -31 -3334 -4216 -3284 -2271 -2477 -2058 375 -821 351 -3441 -1108];
ax1 = subplot(2,1,1);
scatter(x1, y1)
box on
grid on
axis equal
xlims = get(gca, 'XLim')
ax = gca;
ax.XRuler.Exponent = 0;
ax.YRuler.Exponent = 0;
xlims = get(gca, 'XLim')
ax2 = subplot(2,1,2);
scatter(x1, y1)
xlim(xlims)
box on
grid on
ax = gca;
ax.XRuler.Exponent = 0;
set(gcf,'Resize','off') %%%%%%%% this line fixes it for some reason!
linkaxes([ax1,ax2],'x') % want to link x-axis only
%figOut = 'test';
%print(figOut, '-r300', '-djpeg')

Matlab: Fitting two x axis and a title in figure

I am having trouble getting my title to show when I have a figure with two x-axis.
The plot looks good and the axis scales are as I would like them to be but the second axis label and the title end up outside my figure.
How do I get the plot and axis to have the same size and change the size of the figure to include labels and title?
Here is a minimal example:
x1 = linspace(0, 5);
y11 = sin(x1);
y12 = cos(x1);
x2 = linspace(4, 12);
figure(1)
plot(x1, y11, 'r');
hold on
grid on
plot(x1, y12, 'k');
axis([0 5 -1 1.8]);
legend('sin(x)', 'cos(x)');
xlabel('x')
ylabel('y-label');
ax1 = gca;
ax1_pos = ax1.Position;
ax2 = axes('Position', ax1_pos,...
'XAxisLocation', 'top',...
'YAxisLocation', 'right',...
'Color', 'none');
ax2.YColor = 'w';
title('2:nd Harmonics');
line(x2,0,'Parent',ax2,'Color','k')
xlabel('n');
As a workaround you could pre-define the Position property (i.e. size) of the 1st axes before generating the plot so that the title appears correctly even if you add a 2nd axes. For example, right after the call to figure(1) add something like this:
ax1 = axes('Position',[0.11 0.11 0.75 0.75]);
Also, if you wish to print exponent values in the title you can use Latex formatting as follows:
title('2^{nd} Harmonics');
Here is the whole code with output:
clear
clc
close all
x1 = linspace(0, 5);
y11 = sin(x1);
y12 = cos(x1);
x2 = linspace(4, 12);
figure(1)
%// Set axes position manually
ax1 = axes('Position',[0.11 0.11 0.75 0.75]);
plot(x1, y11, 'r');
hold on
grid on
plot(x1, y12, 'k');
axis([0 5 -1 1.8]);
legend('sin(x)', 'cos(x)');
xlabel('x')
ylabel('y-label');
%ax1 = gca;
ax1_pos = get(ax1,'Position');
ax2 = axes('Position', ax1_pos,...
'XAxisLocation', 'top',...
'YAxisLocation', 'right',...
'Color', 'none');
set(ax2,'YColor','w');
%// Notice the Latex formatting to print the exponent
title('2^{nd} Harmonics');
line(x2,0,'Parent',ax2,'Color','k')
xlabel('n');
Then you can resize as you wish; the title stays visible.

Line up differently spaced data when using two axis in MATLAB?

I want to plot an x-axis (bot) that corresponds to values with another x-axis (top), against some data. I want the top and bot axis to refer to the same data point. The following code demonstrates my problem
clc; clear all;
botXaxis = [2.54 1.61 1.00 0.61 0.37];
topXaxis = [159283 97232 59354 36232 22117];
data = [10 10 10 10 10];
hplot = plot(botXaxis,data);
set(hplot,'Linestyle','none','Marker','o');
ax1 = gca;
ax1.XScale = 'log';
ax1.XTick = fliplr(botXaxis);
ax1.XLim = [min(botXaxis) max(botXaxis)];
ax1.XTickLabel = fliplr(botXaxis);
hold on
plot1 = plot([botXaxis(3) botXaxis(3)],get(ax1,'YLim'),'--','color',[0 0 0]);
ax1_pos = ax1.Position;
ax2 = axes('Position',ax1_pos,'XAxisLocation','top','YAxisLocation','right','Color','none');
ax2.XScale = 'log';
set(ax2, 'XTickMode', 'manual');
ax2.XLim = [min(topXaxis) max(topXaxis)];
ax2.XTickMode = 'auto';
ax2.XTick = fliplr(topXaxis);
hold on
plot1 = plot([topXaxis(3) topXaxis(3)],get(ax1,'YLim'),'-','color',[0 0 0]);
% Fix double tick marks
set(ax1,'box','off');
If you run it this plot appears:
I have drawn the straight lines to see if the data lines up correctly. As you can see they do not. I am wondering if there is a way to fix this? The values for data should line up with both topXaxis and botXaxis.
Thanks

Multiple x-axis and y-axis with plots in MATLAB

I am trying to follow MATLAB's documentation here Graph with Multiple x-axes and y-axes to plot with 2 x and y-axes, but instead with plots rather than lines. This is what I have so far:
clear all; close all; clc;
% Arbitrary x's and y's
x1 = [10 20 30 40];
y1 = [1 2 3 4];
x2 = [100 200 300 400];
y2 = [105 95 85 75];
figure
plot(x1,y1,'Color','r')
ax1 = gca; % current axes
ax1.XColor = 'r';
ax1.YColor = 'r';
ax1_pos = ax1.Position; % position of first axes
ax2 = axes('Position',ax1_pos,...
'XAxisLocation','top',...
'YAxisLocation','right',...
'Color','none');
%line(x2,y2,'Parent',ax2,'Color','k') <--- This line works
plot(ax2, x2, y2) <--- This line doesn't work
I've looked the plot documentation 2-D line plot but cannot seem to get plot(ax,__) to help/do what I expect.
The figure ends up not plotting the second plot and the axes end up overlapping.
Any suggestions how to fix this and get 2 axes plotting to work?
I'm currently using MATLAB R2014b.
Finally figured this one out after trying to think about MATLAB's hierarchy of setting things.
The plot seems to reset the axis ax2 properties so setting them before plot doesn't make a difference. line doesn't do this it seems. So to get this to work with plots I did the following:
clear all; close all; clc;
% Arbitrary x's and y's
x1 = [10 20 30 40];
y1 = [1 2 3 4];
x2 = [100 200 300 400];
y2 = [105 95 85 75];
figure
plot(x1,y1,'o', 'MarkerEdgeColor', 'r', 'MarkerFaceColor', 'r')
ax2 = axes('Color','none'); % Create secondary axis
plot(ax2, x2,y2,'o', 'MarkerEdgeColor', 'b', 'MarkerFaceColor', 'b')
% Now set the secondary axis attributes
ax2.Color = 'none'; % Make the chart area transparent
ax2.XAxisLocation = 'top'; % Move the secondary x axis to the top
ax2.YAxisLocation = 'right'; % Move the secondary y axis to the right

Troubles adjusting ticks and gridlines on Matlab 2014b

I'm working on an assignment in which we need to plot curves with gridlines at specific points but I can't figure out how to do it.
This is what I got so far:
figure,
plot(x1,y1)
xlim([0 20]);
ylim([-0.5 1]);
ax = gca;
ax.XTickMode = 'manual';
ax.XTick = [0:5:20];
grid on;
And, on the picture below, is what I needed:
Well, you need to set the YTicks as well.
figure
x1 = 0:0.01:20;
y1 = exp(-x1/4).*sin(x1); plot(x1,y1);
plot(x1,y1)
xlim([0 20]);
ylim([-0.5 1]);
ax = gca;
ax.XTick = [0:5:20];
ax.YTick = [-0.4:0.2:1];
xlabel('$$f(x)$$','interpreter','latex')
ylabel('$$x$$','interpreter','latex')
title('$$f(x) = \exp{(-\frac{x}{4})} \cdot \sin(x)$$','interpreter','latex')
grid on;