Troubles adjusting ticks and gridlines on Matlab 2014b - matlab

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;

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 plot with multiple colormaps

I want to create a plot with pcolor plot with an contour plot on top. Both with different colormaps - pcolor with "hot", the contour with "gray".
I newer Matlab version multiple colormaps are possible.
The code works, however both axis do not overlap, even if the axes positions are in sync.
%% prepare Data
Data2D = peaks(100);
Data2D = Data2D -min(Data2D(:));
Data2D = Data2D/max(Data2D(:)) * 100;
steps = 0:05:100;
xAxis = 1:size(Data2D,2);
yAxis = 1:size(Data2D,1);
figure(1); clf
ax1 = axes;
hold on;
% 3D flat plot
caxis([0 100]);
cmap = fliplr(jet(1000));
colormap(ax1, cmap(1:800,:));
hplot = pcolor(ax1, xAxis, yAxis, Data2D);
shading flat; % do not interpolate pixels
set(ax1,'XLim',[xAxis(1) xAxis(end)]);
set(ax1,'YLim',[yAxis(1) yAxis(end)]);
% colorbar
hcb = colorbar('location','EastOutside');
set(hcb, 'Ylim', [0 100]);
%% contour plot
ax2 = axes; linkaxes([ax1,ax2])
colormap(ax2, flipud(gray(1000)));
[C,hfigc] = contour(ax2, xAxis, yAxis, Data2D,steps);
% Hide the top axes
ax2.Visible = 'off';
ax2.XTick = [];
ax2.YTick = [];
set(hfigc, 'LineWidth',1.0);
hold off;
drawnow
If you didn't use ax2.Visible = 'off' you would probably see that the axes' positions are different, since the first axes are squashed to allow room for the colorbar which the second axes don't have.
TL;DR
You need to set the position properties to be equal
ax2.Position = ax1.Position
Demo
You can simulate this with a blank figure:
1.
% Create figure and first axes, which have a colorbar
figure(1)
ax1 = axes();
colorbar('location', 'eastoutside');
Output:
2.
% Add new axes
hold on;
ax2 = axes();
Output (notice the second axes fills the space of the first + colorbar):
3.
% Make the same, so that the second axes also allow for the colorbar
ax2.Position = ax1.Position;
Output (notice thicker numbers showing they are overlapping fully):

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.

MATLAB: Plotting/Saving X-Y views of mesh function in subplots

As the title says, I'm trying to save the 2-variable slices of a mesh function (as a .jpg, for example) as a subplot. I want to do this using a .m file because I have many plots to generate. I have figured out how to plot the views on their own figures, but I cannot get them to plot properly as subplots within a figure. To illustrate what I mean:
Here are the outputs on individual plots:
3D mesh: 3D MATLAB mesh plot
XY view: XY MATLAB mesh view
YZ view: YZ MATLAB mesh view
XZ view: XZ MATLAB mesh view
And here is my plotting code (not working):
%Ambiguity Surface
fid = figure(fnum);
axes1 = axes('Parent',fid);
view(axes1,[-62.5 28]);
grid(axes1,'on');
hold(axes1,'all');
msh = mesh(taux,fdy,z,'Parent',axes1);
xlabel ('Delay - seconds');
ylabel ('Doppler - Hz');
zlabel ('Ambiguity function (Normalized Magnitude-Squared)');
fname = strcat(name,' (Ambiguity Function z(\tau;F_d))');
title(fname);
cb = colorbar('peer',axes1);
set(get(cb,'ylabel'),'String','Magnitude-Squared (dB)');
hold off;
printFig(fid,fnum,sname)
fnum = fnum + 1;
%Ambiguity Slices
fid = figure(fnum);
hold all;
subplot(2,1,1);
axes1 = axes();
grid(axes1,'on');
view(axes1,[90 0]);
msh = mesh(taux,fdy,z);
xlabel ('Delay - seconds','Visible','off');
ylabel ('Doppler - Hz');
zlabel ('Ambiguity function (Normalized Magnitude-Squared)','Visible','off');
fname = strcat(name,' (Ambiguity Function Slice z(\tau;F_d) # \tau = 128)');
title(fname)
subplot(2,1,2);
axes2 = axes();
grid(axes2,'on');
view(axes2,[0 0]);
msh = mesh(taux,fdy,z);
xlabel ('Delay - seconds','Visible','off');
ylabel ('Doppler - Hz','Visible','off');
zlabel ('Ambiguity function (Normalized Magnitude-Squared)','Visible','off');
cb = colorbar('peer',axes2);
set(get(cb,'ylabel'),'String','Magnitude-Squared');
fname = strcat(name,' (Ambiguity Function Slice z(\tau;F_d) # F_d = 0)');
title(fname)
hold off;
printFig(fid,fnum,slname)
fnum = fnum+1;
printFig() just sets up directory info and does print command.
My code sets up the two subplots and then overlays a full 3-d view of the mesh plot, which is not what I want. I'd like to see two of the views (XZ and YZ) on a single figure.
Thanks for the help!
-Dylan
EDIT:
Per #Andrew_L's suggestion, I modified this in my code:
sp1 = subplot(2,1,1);
axes(sp1);
axes1 = axes();
grid(axes1,'on');
view(axes1,[90 0]);
msh = mesh(taux,fdy,z,'Parent',axes1);
This is repeated for the other subplot. The result is still the same, however. It appears to set up the two blank subplots properly and then display the full pseudo-3D plot over it.
Here is a stripped example very similar to what you are trying to achieve:
%# create axes, and set the view of each
hAx(1) = subplot(221); h = mesh(peaks); view(3)
hAx(2) = subplot(222); copyobj(h,hAx(2)); view(0,90), title('X-Y')
hAx(3) = subplot(223); copyobj(h,hAx(3)); view(0,0) , title('X-Z')
hAx(4) = subplot(224); copyobj(h,hAx(4)); view(90,0), title('Y-Z')
%# set properties of axes
for i=1:4
grid(hAx(i), 'on')
axis(hAx(i), 'tight')
xlabel(hAx(i), 'Delay (sec)');
ylabel(hAx(i), 'Doppler (Hz)');
zlabel(hAx(i), 'Ambiguity function');
end
title(hAx(1), 'Short Tone Ping z(\tau;F_d)')
hc = colorbar('Peer',hAx(1));
set(get(hc,'YLabel'), 'String','Magnitude-Squared (dB)')
When you call axes1 = axes(); right below subplot(2,1,1);, you are setting axes1 to the default full-window axis when you call axes() without any arguments, which is causing the overlap. Instead, try using the handle returned by subplot to generate the axes handle. Try the following code for the second section:
%Ambiguity Slices
fid = figure(fnum);
H1 = subplot(2,1,1);
pos1 = get(H1, 'Position');
set(H1,'Position',[pos1(1) pos1(2) 0.8*pos1(3) pos1(4)]); %leave space for colorbar;
grid on;
msh = mesh(taux,fdy,z);
view([90 0]);
mapping = caxis;
xlabel ('Delay - seconds','Visible','off');
ylabel ('Doppler - Hz');
zlabel ('Ambiguity function (Normalized Magnitude-Squared)','Visible','off');
fname = strcat(name,' (Ambiguity Function Slice z(\tau;F_d) # \tau = 128)');
title(fname)
H2 = subplot(2,1,2);
pos2 = get(H2, 'Position');
set(H2,'Position',[pos2(1) pos2(2) 0.8*pos2(3) pos2(4)]); %leave space for colorbar;
grid on;
msh = mesh(taux,fdy,z);
caxis(mapping);
view([0 0]);
xlabel ('Delay - seconds','Visible','off');
ylabel ('Doppler - Hz','Visible','off');
zlabel ('Ambiguity function (Normalized Magnitude-Squared)','Visible','off');
axes('Position', [0.05 0.05 0.9 0.9], 'Visible', 'off'); %setup axes for colorbar;
caxis(mapping);
cb = colorbar();
ylabel(cb, 'Magnitude-Squared');
fname = strcat(name,' (Ambiguity Function Slice z(\tau;F_d) # F_d = 0)');
title(fname)
printFig(fid,fnum,slname)
fnum = fnum+1;
This (should) at least get everything displayed how you want - I believe that the colorbar scale will not correspond to anything in particular (most likely the number of discrete colors in the bar), so extra code is needed to make sure both plots use the same colormap, and that you change the colormap for the colorbar.

Plot outside axis in Matlab

How to plot something outside the axis with MATLAB? I had like to plot something similar to this figure;
Thank you.
Here is one possible trick by using two axes:
%# plot data as usual
x = randn(1000,1);
[count bin] = hist(x,50);
figure, bar(bin,count,'hist')
hAx1 = gca;
%# create a second axis as copy of first (without its content),
%# reduce its size, and set limits accordingly
hAx2 = copyobj(hAx1,gcf);
set(hAx2, 'Position',get(hAx1,'Position').*[1 1 1 0.9], ...
'XLimMode','manual', 'YLimMode','manual', ...
'YLim',get(hAx1,'YLim').*[1 0.9])
delete(get(hAx2,'Children'))
%# hide first axis, and adjust Z-order
axis(hAx1,'off')
uistack(hAx1,'top')
%# add title and labels
title(hAx2,'Title')
xlabel(hAx2, 'Frequency'), ylabel(hAx2, 'Mag')
and here is the plot before and after:
You can display one axis with the scale you want, then plot your data on another axis which is invisible and large enough to hold the data you need:
f = figure;
% some fake data
x = 0:20;
y = 23-x;
a_max = 20;
b_max = 23;
a_height = .7;
%% axes you'll see
a = axes('Position', [.1 .1 .8 a_height]);
xlim([0 20]);
ylim([0 20]);
%% axes you'll use
scale = b_max/a_max;
a2 = axes('Position', [.1 .1 .8 scale*a_height]);
p = plot(x, y);
xlim([0 20]);
ylim([0 b_max]);
set(a2, 'Color', 'none', 'Visible', 'off');
I had similar problem and I've solved it thanks to this answer. In case of bar series the code is as follows:
[a,b] = hist(randn(1000,1)); % generate random data and histogram
h = bar(b,a); % plot bar series
ylim([0 70]) % set limits
set(get(h,'children'),'clipping','off')% turn off clippings