correct axis range (matlab) - matlab

how can i solve the problem of these two images automatically (with a code adaptable to different data) without having to fix the axes range for each plot (i have millions of these plots)?
problem: axis range should be smaller
problem: axis range should be bigger
also, i need axis to be correctly labeled from the first value to last (see example in comment please)
any help is highly appreciated. thank you so so much.

To set axis limit and visualize chart better you can use axis command like axis([xmin xmax ymin ymax]) where parameters set chart borders. It should help you. More information is here:
http://www.mathworks.se/help/matlab/ref/axis.html

In order to have a complete bounding box use box on.
In order to avoid large empty space around a plot (or no space at all) use xlim and ylim. Try the following:
figure
plot(x,y)
box on
x1 = min(x);
x2 = max(x);
dx = x2-x1;
y1 = min(y);
y2 = max(y);
dy = y2-y1;
fc = 10/100 % this is a factor of 10% of empty space around plot
xlim([x1-dx*fc x2+dx*fc])
ylim([y1-dy*fc y2+dy*fc])
If you want to have a tick value appear at the start and the end of the axis, you could either force it by set(gca,'Xtick',[values]), where values are those ticks you want to show; or by floor and ceil of the xlim and ylim min and max limits above.
Hope this is what you need

Related

How to control the default distance between ticks of the Y axis?

Here is a simple MATLAB code. How to control the default distance between ticks of the Y axis? I want to make it smaller to fit in my paper. Hint: I update the post with 2 picture that shows what I mean (they are the same but the distance between the y axis ticks is smaller in one picture that the other.
x = linspace(-10,10,200);
y = sin(4*x)./exp(x);
plot(x,y)
xlim([0 10])
ylim([-0.4 0.8])
You can control the tick by using the gca object of the plot. Here is an example for xtick. Change 'xtick' to 'ytick':
plot(x,y);
set(gca, 'xtick', [-10:2:10]);
If you want to change the x-axis tick labels with new labels, then you can change the values of the labels as follows:
% specify the ticks first where you want to change
xticks([0 2 4 6 8])
% change the corresponding labels to the required ones
xticklabels({'-1', '-2', '-3', '-4', '-5'})
You can modify the height of the graph, maintaining the number and values of the tick marks, which makes the distance between tick marks smaller.
To do so, set the figure window’s 'Position' property (this is equivalent to dragging the edges of the window to make the figure smaller), and setting the locations of the tick marks manually to prevent MATLAB from reducing their number. For example:
h = gcf; % figure handle
a = gca; % axes handle
ticks = get(a,'YTick');
pos = get(h,'Position');
pos(4) = pos(4) * 0.75; # reduce the size
set(h,'Position',pos);
set(a,'YTick',ticks)
You should also note the PaperPosition, PaperSize and other Paper... properties of the figure, as they are used when printing (also to file). You might want to manually set those properties before creating a PDF or EPS from the graph.
Here is even a simpler way then what #Cris suggested:
ax = axes;
ax.YTickMode = 'manual';
ax.Position(4) = ax.Position(4)*0.75;
by setting the YTickMode to manual you prevent Matlab from updating the ticks upon resizing of the axes. Then you change the hight of the axes by setting the position property directly.

Removing scientific notation in plot axis (Matlab) [duplicate]

Tick labels for ticks bigger than about 10'000, get formatted to 1x10^4 for example. Whereas the exponential part appears above the corresponding axes. This misbehavior has been well described on on matlab central as well, but without a solution.
Thanks for your help.
The 'quick trick'
set(gca, 'YTickLabel',get(gca,'YTick'))
did not work when applied to bar3, as can be seen on the following figure.
EDIT
According to this technical solution page, the recommended way of formatting the tick labels is this (you can use any of the number formatting functions like NUM2STR, SPRINTF, MAT2STR, or any other..)
y = cool(7);
bar(y(:,1)*1e6)
set(gca, 'YTickMode','manual')
set(gca, 'YTickLabel',num2str(get(gca,'YTick')'))
However there seems to be a bug when it comes to the Z-axis (the labels are correctly formatted, but the exponential multiplier is still showing for some reason!)
y = cool(7);
bar3(y*1e6, 'detached')
set(gca, 'ZTickMode','manual')
set(gca, 'ZTickLabel',num2str(get(gca,'ZTick')'))
Finally, there's another workaround where we replace the tick labels with text objects (see this technical solution page as reference):
y = cool(7);
bar3(y*1e6, 'detached')
offset = 0.25; Xl=get(gca,'XLim'); Yl=get(gca,'YLim'); Zt=get(gca,'ZTick');
t = text(Xl(ones(size(Zt))),Yl(ones(size(Zt)))-offset,Zt, num2str(Zt')); %#'
set(t, 'HorizontalAlignment','right', 'VerticalAlignment','Middle')
set(gca, 'ZTickLabel','')
One other trick you can try is to scale your data before you plot it, then scale the tick labels to make it appear that it is plotted on a different scale. You can use the function LOG10 to help you automatically compute an appropriate scale factor based on your plotted values. Assuming you have your data in variables x and y, you can try this:
scale = 10^floor(log10(max(y))); %# Compute a scaling factor
plot(x,y./scale); %# Plot the scaled data
yTicks = get(gca,'YTick'); %# Get the current tick values
set(gca,'YTickLabel',num2str(scale.*yTicks(:),'%.2f')); %# Change the labels
One way to get better control over tick labels, and to avoid the exponential formatting, is to use TICK2TEXT from the File Exchange.
Here's an example:
y = cool(7); %# define some data
ah = axes; %# create new axes and remember handle
bar3(ah,y*1E6,'detached'); %# create a 3D bar plot
tick2text(ah, 'ztickoffset' ,-1.15,'zformat', '%5.0f', 'axis','z') %# fix the tick labels

Distance between axis number and axis in MATLAB figure

I struggle a little bit with overlapping axis numbers of the y and x axis like it is shown in the image. I'd like to keep the size of the numbers and therefore think that simply shifting the numbers away from the axis itself would be an appropriate way to handle this issue.
Is there a possibility to do that?
Thanks in advance,
Joe
Here is a little workaround using text annotations. Basically you clear the current XTick labels and replace them with similar labels, but you can specify the distance from the axis:
clc
clear
close all
x = 1:20;
hPlot = plot(x,sin(x));
set(gca,'xaxisLocation','top');
set(gca,'XTickLabel',[]); %// Clear current XTickLabel
ylim = get(gca,'YLim'); %// Get y limit of the plot to place your text annotations.
for k = 2:2:20
text(k,ylim(2)+0.1,num2str(k),'HorizontalAlignment','Center') %// Play with the 'ylim(1) -0.1' to place the label as you wish.
end
Giving this:
Of course now it's exaggerated and you can do the same for the y axis if you want (using the 'XLim' property of the current axis,gca).

Finding the limits of automatically-adjusted axes in a MATLAB plot

I'm creating a 2d MATLAB plot. I'm setting the limits of my x axis, and letting my y axis auto-adjust (by setting its limits to [-inf inf]). After creating my plot, I need to check what my y axis has auto adjusted to (as I'm going to create a heatmap to put under my plot).
Unfortunately, ylim (and similar functions) only produce [-inf inf], not whatever the axes have adjusted to.
Some code which reproduces this problem (much more simply than my actual code) is:
function createplot(xbounds)
x = xbounds(1):0.5:xbounds(2);
y = x.^2;
plot(x,y);
axis([xbounds,-inf,inf]);
createplot([0,10])
which produces a parabolic plot with y limits = [0,100]. However, ylim = [-inf, inf].
Any help would be appreciated!
/ Wilbur
As #Shai suggested, axis can give info regarding the ylimits without the need to set them to [-inf,inf] or use axis to set the x-axis bounds:
xbounds=[1 10]
x = xbounds(1):0.5:xbounds(2);
y = x.^2;
plot(x,y);
xlim([xbounds(1) xbounds(2)]);
v=axis
v =
1 10 0 100
Looking at #natan's answer I think the solution to your problem is
Do not use [-inf inf] for auto-adjusting axis limits.
If you want Matlab to auto adjust some of your axes limits and manually set others, then you should use either xlim, ylim or zlim for the specific axis you wish to set and leave all the other unchanged so Matlab can set them automatically.
This way you will not override the values Matlab assigns to those axes and you will be able to read them using axis, xlim, ylim or zlim.
Please see #natan's answer for corrected code.

Fixing the Radial Axis on MATLAB Polar Plots

I'm using polar plots (POLAR(THETA,RHO)) in MATLAB.
Is there an easy way to fix the range for the radial axis to say, 1.5?
I'm looking for something analogous to the xlim, ylim commands for cartesian axes. Haven't found anything in the docs yet.
this worked for me... i wanted the radius range to go to 30, so i first plotted this
polar(0,30,'-k')
hold on
and then plotted what i was actually interested in. this first plotted point is hidden behind the grid marks. just make sure to include
hold off
after your final plotting command.
Here's how I was able to do it.
The MATLAB polar plot (if you look at the Handle Graphics options available) does not have anything like xlim or ylim. However, I realized that the first thing plotted sets the range, so I was able to plot a function with radius range [-.5 .5] on a [-1 1] plot as follows:
theta = linspace(0,2*pi,100);
r = sin(2*theta) .* cos(2*theta);
r_max = 1;
h_fake = polar(theta,r_max*ones(size(theta)));
hold on;
h = polar(theta, r);
set(h_fake, 'Visible', 'Off');
That doesn't look very good and hopefully there's a better way to do it, but it works.
Simple solution is to make a fake graph and set its color to white.
fake=100;
polar(0,fake,'w');
hold on;
real=10;
polar(0,real,'w');
In case anyone else comes across this, here's the solution:
As Scottie T and gnovice pointed out, Matlab basically uses the polar function as an interface for standard plots, but with alot of formatting behind the scenes to make it look polar. Look at the values of the XLim and YLim properties of a polar plot and you'll notice that they are literally the x and y limits of your plot in Cartesian coordinates. So, to set a radius limit, use xlim and ylim, or axis, and be smart about the values you set:
rlim = 10;
axis([-1 1 -1 1]*rlim);
...that's all there is to it. Happy Matlabbing :)