Search code examples
matlabbar-chartmatlab-figure

How to custom Xtick for bar plotting in matlab


I have used bar plotting (grouped style), as shown in the figure below using this my code.

y = [200 200 200 192 160 128 96 64 48 32 96 64 24 48 32;
     48 64 96 48 32 24 24 64 16 24 48 32 48 64 24;
     6 6 2 4 4 6 12 8 2 4 8 6 16 12 6;
   ];
[rows,cols] = size(y);
n = NaN(rows,cols);
c = {'r' 'g' 'b'};
bh = cell(rows,1);
lh = cell(rows,1);

hold on;
for k = 1:rows
    curr = n;
    curr(k,:) = y(k,:);
    bar1 = bar(curr,'FaceColor',rand(1,3));
    bh{k} = bar1;
    lh{k} = bar1(1);
end
hold off;

legend([lh{:}],{'1st group','2nd group', '3rd group', },...
    'fontweight','bold','Location','best','FontSize',12);
xlabel('Samples (45 Locations) ','fontweight','bold','FontSize',12);
ylabel('Distance Error (meters)','fontweight','bold','FontSize',12);

enter image description here

Thus, I need to do the following:

  1. put specific numbers under each bar for each group along the x-axis
  2. change the value "200" only at Y-axis into "NaN", while the remaining values not changed.

Solution

  • Here is an alternative and more simple way to create this bar plot:

    y = [200 200 200 192 160 128 96 64 48 32 96 64 24 48 32;
        6 6 2 4 4 6 12 8 2 4 8 6 16 12 6;
        48 64 96 48 32 24 24 64 16 24 48 32 48 64 24];
    [rows,cols] = size(y);
    col_id = reshape(1:cols*rows,[],rows); % generate number for the bars by group
    w = 3; % amount of spacing between groups
    col_pos = col_id+(0:rows-1)*w; % set the x-position for all bars
    % if your Matlab version is <2016b, uncomment the folloing line instead of the line above:
    % col_pos = bsxfun(@plus,col_id,(0:rows-1)*w);
    hold on
    for k = 1:rows
        bar(col_pos(:,k),y(k,:),'FaceColor',rand(1,3));
    end
    hold off
    ax = gca;
    ax.YTickLabel{end} = 'NaN'; % set the last y-tick to 'NaN'
    ax.XTick = col_pos(:); % place x-ticks only under the bars
    ax.XTickLabel = col_id(:); % set the x-ticks labels to the bar's id
    xlim([0 col_pos(end)+1]) % remove extra space on the right
    legend({'1st group','2nd group', '3rd group', },...
        'fontweight','bold','Location','best','FontSize',12);
    xlabel('Samples (45 Locations) ','fontweight','bold','FontSize',12);
    ylabel('Distance Error (meters)','fontweight','bold','FontSize',12);
    

    The result:

    enter image description here