Better way to autoscale x axis a histogram

13 次查看(过去 30 天)
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)

回答(1 个)

Kirby Fears
Kirby Fears 2015-11-24
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 个评论
Jason
Jason 2015-11-25
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 2015-11-25
编辑:Kirby Fears 2015-11-25
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."

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Annotations 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by