Legend captions displayed in bar stack order for bar-line plot

1 view (last 30 days)
Here is my code below (as a note, the label naming right now is nonsense). How do I edit this code such that I can display the legend Bar labels in rising stack order, i.e. the legend box would show:
  • Spain Temp
  • England Temp
  • Iceland Temp
  • GDP
I would also like this to account for a variable number of temperatures (i.e. stacks) with one line plot.
I would greatly appreciate any guidance on this problem. I have tried to use the flip method but I always want to keep my GDP label in the same place. Thank you!
colororder({'k','k'})
barLegend = {'Iceland', 'England', 'Spain'};
totalLegend = cell(1, numel(barLegend) + 1);
for i = 1:numel(barLegend)
totalLegend{i} = [barLegend{i} ' Temperature'];
end
totalLegend{end} = 'GDP';
b = [1:4; 10:13; 21:24];
a = [74 68 63 56];
x = [1:4];
yyaxis left
bar(x, b, 'stacked')
colororder('default')
grid on
grid minor
hold on
yyaxis right
plot(x,a)
legend(totalLegend)
hold off

Accepted Answer

Arijit Bhattacharyya
Arijit Bhattacharyya on 7 Sep 2021
@Walter Roberson Thank you for your guidance, your code still gives me indexing errors, but I believe that I have managed to solve it. It required making an extra variable for the plot function as well and indexing to that specific variable in an array concatenation.
colororder({'k','k'})
barLegend = {'Iceland', 'England', 'Spain'};
totalLegend = cell(1, numel(barLegend) + 1);
for i = 1:numel(barLegend)
totalLegend{i} = [barLegend{i} ' Temperature'];
end
totalLegend{end} = 'GDP';
b = [1:4; 10:13; 21:24];
a = [74 68 63 56];
x = [1:4];
yyaxis left
h = bar(x, b, 'stacked');
order = [3 2 1 4];
colororder('default')
grid on
grid minor
hold on
yyaxis right
p = plot(x, a);
legend([h(order(1:end-1)), p(1)], [totalLegend(order(1:end-1)), ...
totalLegend(order(end))], 'Location', 'best')

More Answers (1)

Walter Roberson
Walter Roberson on 6 Sep 2021
Edited: Walter Roberson on 6 Sep 2021
try
h = bar(x, b, 'stacked');
order = [3 2 1 4];
legend(h(order), totalLegend(order))

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!