Search code examples
matlabplotmatlab-figure

Enforcing different bar graphs side by side


I have 3 temperature values for January, one for February and one for march. I want to draw them on one bar graph. I used the overlay method in matlab to draw the 3 values for January. But when I plot the other 2 months, they overlay January. How to enforce February and march values to be side by side to January.

Update: I added the output of running the code below, and changes I want to have

temp_high = [12.5]; 
w1 = 0.5; 
bar(x,temp_high,w1,'FaceColor',[0.2 0.2 0.5])

temp_low = [10.7];
w2 = .25;
hold on
bar(x,temp_low,w2,'FaceColor',[0 0.7 0.7])

temp_very_low = [7.1];
w2 = .1;
hold on
bar(x,temp_very_low,w2,'FaceColor',[0 0 0.7])

ax = gca;
ax.XTick = [1]; 
ax.XTickLabels = {'January'};
ax.XTickLabelRotation = 45;

name={'feb';'march'};

y=[5 ;
 3   ]

bar_handle=bar(y);
set(gca, 'XTickLabel',name, 'XTick',1:numel(name))

ylabel('Temperature (\circF)')
legend({'jan 1-with 1-instance','jan 1-with 2-instance','jan 1-with 3-instance','feb', 'march'},'Location','northwest')

enter image description here


Solution

  • The main issue with your code is in bar(y). The two values in y are implicitly plotted at the x values 1 and 2. What you want is, to plot them at 2 and 3. So, you must explicitly specify these values.

    I took the liberty to re-organize your code by collecting all temperature data, widths, and colors in variables. In doing so, all bar plots can be done within a single loop.

    Here's the code:

    figure(1);
    hold on;
    
    % Collect all data.
    temp = [1 12.5; 1 10.7; 1 7.1; 2 5; 3 3];
    w = [0.5 0.25 0.1 0.5 0.5];
    c = [0.2 0.2 0.5; 0 0.7 0.7; 0 0 0.7; 1 0 0; 0 0 1];
    
    % Plot all temperatures within single loop.
    for ii = 1:numel(w)
      bar(temp(ii, 1), temp(ii, 2), w(ii), 'FaceColor', c(ii, :));
    end
    
    % Decoration.
    ticks = [1 2 3];
    xlabels = {'January', 'February', 'March'};
    set(gca, 'XTick', ticks, 'XTickLabel', xlabels);
    
    ylabel('Temperature (\circF)');
    legend({'jan 1-with 1-instance', 'jan 1-with 2-instance', 'jan 1-with 3-instance', 'feb', 'march'}, 'Location','northwest');
    
    hold off;
    

    The output I get, looks like this:

    Output

    Hope that helps!