Search code examples
matlabbar-chartmatlab-figureaxis-labels

Matlab - Bar chart with two plots and two axis


I am plotting two arrays in one plot. The bar plot must show two y-axis as well as the bars next to each other. The problem occurs when I want to implement both requirements.

I can either plot the bars together with for example

Y = [5,2; 8,7; 9,8; 5,5; 4,3];
figure
bar(Y)

Or I can create two y-axis (which I do currently with my data):

y = [lr_flights2018, lr_income2018]; 
yyaxis left
b = bar(1:length(y),lr_flights2018);
ylabel('Life Rating/flights ratio')
yyaxis right
p = bar(1:length(y),lr_income2018);
ylabel('Life Rating/income ratio')
set(gca, 'XTick', 1:length(y))
set(gca,'XTickLabel',{countries{:,1}})
xtickangle(90)
title('Correlations with life rating');

In the latter yyaxis separates the plots which results in the two plots stacked together. I want the plots to stand side by side for each bin as can be seen in this example.


Solution

  • You can do this by manipulating the x position and the bar width

    I manipulated your Y data as shown below, and made some new labels for the countries which you didn't provide in your example

    figure;
    Y = [5,2; 8,7; 9,8; 5,5; 4,3];;
    lr_flights2018 = Y(:,1);
    lr_income2018 = Y(:,2);
    y = [lr_flights2018, lr_income2018]; 
    yyaxis left
    b = bar((1:length(y))+0.125,lr_flights2018, 'barwidth', 0.25);
    ylabel('Life Rating/flights ratio')
    yyaxis right
    p = bar((1:length(y))-0.125,lr_income2018, 'barwidth', 0.25);
    ylabel('Life Rating/income ratio')
    set(gca, 'XTick', 1:length(y))
    str = strread ( sprintf ( '%i\n', [1:5] ), '%s', 'delimiter', '\n' )
    set(gca,'XTickLabel',str)
    xtickangle(90)
    title('Correlations with life rating');
    

    example output from r2018b