Search code examples
matlabmatlab-figurefigure

How to make the bar have the same color in the same group when plot in Matlab


enter image description here

In this figure, we have two groups of bars, A and B. How to make the bars in group A have the same color a, and bars in group B have the same color b. And how to produce the legend for these two groups.

Thanks.

code:

latency = [62.36 80 793.17 215.15 199.39 ; 
           43.21 50 221 206.90 10 ]; 
h = bar(latency, 1);
set(h, 'FaceColor',[64 224 208]./255,'LineWidth', 0.7)
set(gca,'linewidth',0.8,'Fontname', 'Arial', 'FontWeight', 'bold');
set(gca,'XLim',[0.5, size(latency,1)+0.5], ...
   'XTick',[0.69:0.155:1.4 1.70:0.155:2.3], ...
   'XTickLabel',{'A', 'B', 'C', 'D', 'E', 'A', 'B', 'C', 'D', 'E'});
box on;

Solution

  • You can use two bar plots in one axes:

    figure;
    h1 = bar(1:5, latency(1,:));
    hold on;
    h2 = bar(7:11, latency(2,:));
    ax = gca;
    ax.XTick = [1:5, 7:11]
    ax.XTickLabel={'A','B','C','D','E','A','B','C','D','E'}
    

    You can use h1 and h2 to access and modify the Bar objects.

    enter image description here