Search code examples
matlabbar-chartstackedbarseries

plot a stacked bar chart in matlab that shows all the values


Hi I have the following code in Matlab

CC_monthly_thermal_demand = [495 500 500 195 210 100 70 65 85 265 320 430]';
AD_monthly_thermal_generation_250 = [193 193 193 193 193 193 193 193 193 193 193 193]';
figure;
bar(1:12,AD_monthly_thermal_generation_250)
hold on
bar(1:12,CC_monthly_thermal_demand,'r')
set(gca,'XTickLabel',{'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug',' Sep', 'Oct', 'Nov',' Dec'},'FontSize',18)
title('Seasonal Anaerobic Digestion (250kWe) Thermal Energy Supply to Demand - 2012','FontSize',22)
ylabel('Thermal Energy (MWhe)')
legend('250 kWth Supply','Thermal Energy Demand')
grid on
axis([0 13 0 600])

I am trying to plot a stacked bar chart that shows the colour of each variable for every bar. However, for the bars where the "AD_monthly_thermal_generation_250" is a lower value than the "CC_monthly_thermal_demand" the "AD_monthly_thermal_generation_250" colour is completely covered by the "CC_monthly_thermal_demand" and so I can't see these values. Is it possible to be able to see them?

Thank you


Solution

  • Combine the inputs together such that each series is a column, then use the option 'stack':

    A = [495 500 500 195 210 100 70 65 85 265 320 430]';
    B = [193 193 193 193 20  193 193 193 193 193 193 193]';
    bar([B,A],'stacked')
    

    EDIT addressing comment:

    % Create random data and filler
    A      = randi(100,10,1);
    B      = randi(100,10,1);
    mxA    = max(A);
    filler = mxA-A;
    
    % Plot stacked bar chart
    h = bar([A,filler,B],'stacked');
    
    % Set the filler to transparent
    set(h(2),'Face','none','Edge','none')
    
    % Set y-labels
    yticks = linspace(0,max(B),5) + mxA;
    set(gca,'Ytick', [linspace(0,mxA,5) yticks(2:end)],'YtickL', [linspace(0,mxA,5) yticks(2:end)-mxA])
    

    enter image description here