How to assign error bar at middle of histogram?

2 次查看(过去 30 天)
Hello everyone,
I am trying to plot the histogram with the error bar at the middle point of histogram, and I used 'bar' syntax to get the plot, but couldn't get what I was looking for. Any help will be really appreciated.
% bin edges
bi = 0 :3: 175;%bin interval
% absolute frequencies
af1 = histc(VarName1, bi);
af2 = histc(VarName2, bi);
af3 = histc(VarName3, bi);
af4 = histc(VarName4, bi);
af5 = histc(VarName5, bi);
%VarName1, VarName2,VarName3,VarName4,VarName4 are my five distribution of data
mean=(af1+af2+af3+af4+af5)/5.0;
error=sqrt(((mean-af1).^2+(mean-af2).^2+(mean-af3).^2+(mean-af4).^2+(mean-af4).^2)/5);
%histogram(mean,be)
bar(bi,mean,'histc');
hold on
errorbar(bi,mean,error,'k','linestyle','none')
Thanks,
AG

回答(1 个)

OCDER
OCDER 2018-5-16
编辑:OCDER 2018-5-16
Here are some suggestions. To see what each line is doing, remove the ";".
%Store your data in cells so you can use loops. Example:
VarName = cell(1, 5);
for j = 1:5
VarName{j} = randi(175, 100, 1);
end
%Label your variables with 1st-letter cap, to prevent overwriting matlab
%functions. For instance, you had "mean = (af1+af2+..." which would
%override the "mean.m" matlab function! This leads to a lot of bugs.
Bin = 0:3:175;
AF = zeros(length(Bin), length(VarName)); %Store your binned data in a matrix
for j = 1:5
AF(:, j) = histc(VarName{j}, Bin);
end
Mean = mean(AF, 2);
%error=sqrt(((mean-af1).^2+(mean-af2).^2+(mean-af3).^2+(mean-af4).^2+(mean-af4).^2)/5
%Notice you have a typo. (mean-af4).^2 comes twice.
%To prevent coding error, use following practices:
Error = sqrt(sum((Mean-AF).^2, 2)/5)
%Error = std(AF, [], 2); %Did you want standard dev?
%Plot data and store the handles as variables. Makes it easier to adjust.
Bx = bar(Bin, Mean, 'histc');
hold on
Shift = diff(Bin(1:2))/2; %Need to shift your error bar to center it
Ex = errorbar(Bin+Shift, Mean, Error, 'k', 'linestyle', 'none');
hold off
%Adjust plots via those handles. Example:
Bx.FaceColor = [1 1 1]; %Make bars white
Ex.Color = [1 0 0]; %Make error bars red
  6 个评论
Ashok Gurung
Ashok Gurung 2018-6-18
Hey OCDER, I know it takes a long time to reply back, apology for that. I checked the code today, and it's working now. Thanks for the help and I really appreciate that. THX AG

请先登录,再进行评论。

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by