Distance between axis number and axis in MATLAB figure - matlab

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

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

How to set x and y values when using bar3 in Matlab?

Quick version
How can I control the x- and y-values for a 3-d bar plot in Matlab?
Details
Say we have an 10 x 20 data matrix and we plot it using bar3, and we want to set the x- and y-values. For instance:
foodat = rand(10,20);
xVals = [5:14];
yVals = [-3:16];
bar3(xVals, foodat);
xlabel('x'); ylabel('y');
Is there a way to feed it the yVals as well? Otherwise the y axes always defaults to [1:N].
Note I don't just want to change the labels using XTickLabel and YTickLabel. I need to change the actual values on the axes, because I am plotting multiple things in the same figure. It isn't enough to just change how the (wrong) axis ticks are labeled. So this is different from issues like this:
How can I adjust 3-D bar grouping and y-axis labeling in MATLAB?
Other things I have tried
When I try changing the xvals with:
set(gca,'XTick', xVals)
set(gca,'YTick', yVals)
The values are taken in, but actually show up on the wrong axes, so it seems x and y axes are switched using bar3. Plus, it is too late anyway as the bar graph was already plotted with the wrong x- and y-values, so we would end up giving ticks to empty values.
Note added
Matlab tech support just emailed me to let me know about the user contributed function scatterbar3, which does what I want, in a different way than the accepted answer:
http://www.mathworks.com/matlabcentral/fileexchange/1420-scatterbar3
I found a way of doing it. Ill give you a piece of code, then you'll need to "tidy up" , mainly the axis limits and the Xticks, as bar3 does set up the Xticks inside, so if you want others you'll need to set them manually yourself.
So the trick here is to get the Xdata from the bar3 handle. The thing here is that it seems that there is a handle for each row of the data, so you need to iterate for each of them. Here is the code with the current output:
foodat = rand(20,10);
xVals = [5:14];
yVals = [-3:16];
% The values of Y are OK if called like this.
subplot(121)
bar3(yVals, foodat);
subplot(122)
h=bar3(yVals, foodat);
Xdat=get(h,'XData');
axis tight
% Widdth of barplots is 0.8
for ii=1:length(Xdat)
Xdat{ii}=Xdat{ii}+(min(xVals(:))-1)*ones(size(Xdat{ii}));
set(h(ii),'XData',Xdat{ii});
end
axis([(min(xVals(:))-0.5) (max(xVals(:))+0.5) min(yVals(:))-0.5, max(yVals(:))+0.5])
Note: Y looks different but is not.
As you can see now the X values are the ones you wanted. If you'd want other size than 1 for the intervals between them you'd need to change the code, but you can guess how probably!

How to merge different plot but same y axis in matlab

I'm always see this kind of graph in XRD plot:
and i'm wondering how they do that?, if you have different XRD plot and assuming having the same y axis, can matlab do this? thanks.
Here is a way to do it.You can customize it as you want, but this should hopefully get you going.
First create an axes and change its position/size inside the figure, shifting it upward to make room for the 2nd axes as well as removing the x and y labels that you don't want. Then create a 2nd axes with specified position/size to make it fit below the 1st one.
Sample code:
clear
clc
%// Generate dummy data
x = 1:2:100;
y1 = rand(1,numel(x));
figure;
%// Make an axes and set its position
haxes1 = axes('Position',[.1 .1 .8 .7],'Color',[1 1 1])
%// Plot 1st curve
plot(x,y1,'Parent',haxes1)
%// Remove box and labels
box off
set(gca,'XTickLabel','','XTick',[],'YTick',[])
hold on
%// Get current axes position. You set it so you could get the parameters
%// directly as well.
axes1Pos = get(gca,'Position');
%// Shift 1st axes upward
set(gca,'Position',[axes1Pos(1) 2.6*axes1Pos(2) axes1Pos(3) axes1Pos(4)])
%// Change the poisition/size of the 2nd axes to fit below the 1st one
haxes2 = axes('Position',[axes1Pos(1) axes1Pos(2)/2.5 axes1Pos(3) axes1Pos(4)/2.5]) ;
%// Use linspace to generate colored points to use with scatter.
c = linspace(1,10,length(x));
%// Add 2nd plot and keep only x label
scatter(x,rand(1,numel(x)),40,c,'filled')
set(gca,'YTick',[])
box off
%// Place a ylabel for both axes
text(-4, 1.7,'Super nice y label','rotation',90,'FontSize',16,'HorizontalAlignment','center')
Sample output:
There are other ways to do this as well.
Hope that helps!

correct axis range (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