Why does my histogram become incorrect when I change the y-axis scaling to 'log'?
5 views (last 30 days)
Show older comments
When I execute the following code:
hist(randn(100,1));
set(gca,'yscale','log')
the bars are incorrectly displayed; the histogram bars either become lines or disappear entirely.
Accepted Answer
MathWorks Support Team
on 18 Jun 2013
The ability to create a log-scale histogram is not available in MATLAB. There are a couple of ways to work around this issue,
1. Change the underlying patch object vertices, as follows:
x = -5:0.1:5;
y = randn(100000,1);
hist(y,x);
%Workaround
% Get histogram patches
ph = get(gca,'children');
% Determine number of histogram patches
N_patches = length(ph);
for i = 1:N_patches
% Get patch vertices
vn = get(ph(i),'Vertices');
% Adjust y location
vn(:,2) = vn(:,2) + 1;
% Reset data
set(ph(i),'Vertices',vn)
end
% Change scale
set(gca,'yscale','log')
In this case, note that if the histogram only reports one instance of a value in one of its bins, then you will not see this value. This is because 1 (10^0) is the new baseline value for the y-axis.
2. Use SURFACE objects as shown below in an example:
x1 = [0 1]; y1 = [1 5];
x2 = [1 2]; y2 = [1 15];
x3 = [3 4]; y3 = [1 8];
surface('Xdata',x1,'Ydata',y1,'Zdata',zeros(2),'Cdata',ones(2)*.5)
surface('Xdata',x2,'Ydata',y2,'Zdata',zeros(2),'Cdata',ones(2)*.6)
surface('Xdata',x3,'Ydata',y3,'Zdata',zeros(2),'Cdata',ones(2)*.7)
set(gca,'yscale','log')
set(gca,'ylim',[0 100])
Note that if the boundaries of y include zero, then the surface objects are not drawn correctly since log(0) = -inf.
0 Comments
More Answers (0)
See Also
Categories
Find more on Histograms in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!