Better way to autoscale x axis a histogram

18 views (last 30 days)
Jason
Jason on 24 Nov 2015
Edited: Kirby Fears on 25 Nov 2015
I am trying to "autoscale" the x-axis of a histogram on an axes component. I think I have done it using for loops but was wondering if there was a more elegant way to do it.
I first get the histogram data from the axes.
axes(handles.axes2);
barObj= findobj(gca, 'type', 'bar');
x=get(barObj,'XData')';
y=get(barObj,'YData')';
Determine max x & max y
mxy=max(y);
mxx=max(x);
Find index of max Y value so can get its "x" value. Also define a level value, below which I will declare the "bounds" of the histogram to then pass to xlim.
idx = find(y==mxy);
level=0.01*mxy
Get upper limit of X axis: The idea is to count x from the x location where Y is max and count outwards until 3 consecutive Y values less than level are obtained.
%Get upper limit
for i=idx:max(x)-3
i=i+1;
y1=y(i);
y2=y(i+1);
y3=y(i+2);
if(y1&y2&y3<level)
indexH=i;
break
end
end
Likewise for the lower X value bound:
%Get lower limit
indexL=0; %set incase not found
for i=0:idx
i=i+1;
y1=y(i);
y2=y(i+1);
y3=y(i+2);
if(y1&y2&y3>level)
indexL=i;
break
end
end
Now rescale the x -axis
xlim([indexL indexH])
Here is the original histogram
and what I am trying to achieve (more elegantly)

Answers (1)

Kirby Fears
Kirby Fears on 24 Nov 2015
After plotting:
axis tight
axis 'auto y'
axis tight makes both x and y axes fit the min/max values of the axis. Then 'auto y' reverts the y axis scale back to the standard setting.
  2 Comments
Jason
Jason on 25 Nov 2015
Hi, thanks for your suggestion. Unfortunately I have an outlier at a value of x=340 (see the top graph which is autoscaled in x). So your suggestion just duplicates the top image.
Kirby Fears
Kirby Fears on 25 Nov 2015
Edited: Kirby Fears on 25 Nov 2015
Have you considered excluding outliers before plotting? It makes sense to apply your "selection" logic to the data itself instead of the axis boundaries:
"Get upper limit of X axis: The idea is to count x from the x location where Y is max and count outwards until 3 consecutive Y values less than level are obtained."

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!