Search code examples
matlabgraphbar-chartoverlapping

How to increase bar width without overlapping in a MATLAB bar graph?


How can you increase the width of the bars in a bar graph in MATLAB without causing the bars to overlap? The script below increases the bar width but the bars overlap:

graph = [ 1 2 ; 3 4 ; 5 6 ; 7 8 ];
bar(graph,'BarWidth',2);

Solution

  • The only way I know to do this is via multiple calls to bar.

    function h=BarSpecial(data, overallWidth )
        colour = {'r','b'};
        [r,c] = size(data);
        h = zeros(c,1);
        width = overallWidth / c;
        offset = [-width/2 width/2];
        for i=1:c
            h(i) = bar(data(:,i),'FaceColor',colour{i},'BarWidth',width);   
            set(h(i),'XData',get(h(i),'XData')+offset(i));
            hold on               
        end    
    end
    

    The following will generate a bar chart with the bars occupying 90% of the total space.

    BarSpecial(graph,0.9)
    

    The function BarSpecial as written is not general purpose but could be extended to handle a wider range of input data.