Search code examples
matlabplothistogram

Issue with plotting error bar on a bar histogram


I try to plot standard deviation on each bar of an histogram. For the moment, I start from the following histogram :

Original histogram

To get this histogram, I have used the y array (of size 8x3) like this :

% Abscissa
x=[2 4 8 16 32 64 128 256];
% Plot histogram
figure(1);
hbar=bar(log2(x),y(1:8,1:3),'b');

Now, I want to plot the standard deviation on each of the 24 bars. I have an array deviation of size (8x3).

I tried to do :

% Abscissa
x=[2 4 8 16 32 64 128 256];
% Plot histogram
figure(1);
hbar=bar(log2(x),y(1:8,1:3),'b');
hold on;
% Plot standard deviation
errorbar(log2(x),y(1:8,1:3),deviation(1:8,1:3));

But I get the following error :

Error using errorbar>checkSingleInput (line 264)
XData must be the same size as YData.

Error in errorbar (line 94)
x = checkSingleInput(x, sz, 'XData');

Error in plot_benchmark (line 29)
errorbar(log2(x),y(1:8,1:3),deviation(1:8,1:3));

It seems that errorbar doesn't support 2D array. If this is the case, how to circumvent this issue and be able to plot error bar for each of the 24 bars of histogram shown on image above ?

UPDATE 1 : I tried to adapt the solution given in possible duplicate by doing :

hbar=bar(log2(x),y(1:8,1:3),'b');
hold on;
% Compute x position for each bar
for i=1:8
   x1=get(get(hbar(i),'children'),'xdata');
   barsx(i,1:3)=mean(x1,1)
end
% Plot standard deviation
errorbar(barsx,y(1:8,1:3),deviation(1:8,1:3));

but the array barsx is empty. Why is this?


Solution

  • You can create error bar using barweb function. In the below code, I use random data same as your array dimensions to evaluate my solution.

    % Abscissa
    y = rand(8,3);
    deviation = y-(y/2);
    x=[2 4 8 16 32 64 128 256];
    % Plot histogram
    figure(1);
    hbar=bar(log2(x),y(1:8,1:3),'b');
    hold on;
    % Plot standard deviation
    barweb(y,deviation,[],x);
    

    There is mistake in barweb you can find resolve here.