Search code examples
matlabbar-chartvisualizationmatlab-figurep-value

How to add distance lines between bar graphs


I would like to indicate p-values between multiple bar graphs as in the figure below:

Input 1

But I have not found relevant commands about this on MATLAB's page on bar graphs.

Here is my code for the bar graphs and the standard deviation graphics:

x = 1:3;
y = [17.5, 97.5, 100];
std = [23.84848004, 10.89724736, 0];

figure
hold on
bar(x,y)
errorbar(y,std,'.')

XTickLabel={'1' ; '2'; '3' ; '4'};
XTick=2:4:15
set(gca, 'XTick',XTick);
set(gca, 'XTickLabel', XTickLabel);

Solution

  • There is no such function that I know of, but it is easy to write one:

    function [hl,ht] = overbar(x1, x2, y, txt)
    sz = get(gca,'FontSize');
    bg = get(gca,'Color');
    d = 2; % size of hook, change depending on y axis scaling
    hl = line([x1,x1,x2,x2], [y,y+d,y+d,y]);
    ht = text((x1+x2)/2, y+d, txt, ...
              'HorizontalAlignment','center', ...
              'VerticalAlignment','middle', ...
              'FontSize',sz, ...
              'BackgroundColor',bg);
    end
    

    This function uses the axes' font size and color properties to determine how to draw the text. It first draws the line, then draws the text on top, using a solid background so that the line appears interrupted by the text.

    This is how you would use it:

    x = 1:3;
    y = [17.5, 97.5, 100];
    std = [23.84848004, 10.89724736, 0];
    
    figure
    hold on
    set(gca, 'FontSize',16)
    bar(x, y)
    errorbar(y, std, '.')
    
    set(gca, 'ylim',[0,150]);
    
    XTickLabel = {'A', 'B', 'C'};
    set(gca, 'xtick',x, 'XTickLabel',XTickLabel);
    
    overbar(1 ,2, 120, 'p=0.037');
    overbar(2, 3, 130, 'p<0.0001');
    overbar(1, 3, 140, 'p<0.0001');
    

    output plot