How to plot a legend with multiple confidence intervals?

7 views (last 30 days)
I have a plot with a line and 2 confidence intervals (90% and 68%). So, 5 lines in total. I would like to display only the legend for the central line. There are many answers around the web but I didn't find one that fixes my issue.
This is my code I tried without success:
X.label = [0 10 20 30];
x= xlsread('x.xlsx')
plotarea_b(x,X.label);
ylabel('%')
title('X1', 'FontWeight', 'Normal')
legend({'', '', '', '', 'X1'}, 'Location', 'southoutside')
Attached I provide the function I use to plot ('plotarea_b') and the dataset of the series I am plotting ('x.xlsx').
Can anyone help me?
Thanks!

Accepted Answer

Adam Danz
Adam Danz on 14 Nov 2020
Edited: Adam Danz on 14 Nov 2020
Use the graphics object handles to specify which objects you want in the legend.
See 4 "% ADDED" comments below
X.label = [0 10 20 30];
x= xlsread('x.xlsx');
[output,ha1,ha2,ha3] = plotarea_b(x,X.label); % ADDED
ylabel('%')
title('X1', 'FontWeight', 'Normal')
legend([ha1(2),ha2(2),output],{'error1','error2', 'X1'}, 'Location', 'southoutside') % ADDED
function [output,ha1,ha2,ha3] = plotarea_b(datamat,xlabel) % ADDED
ha1 = area([datamat(:,1) datamat(:,end)-datamat(:,1)],'linestyle','none');
hold on;
set(ha1(1), 'FaceColor', 'none');
set(ha1(2), 'FaceColor', [0.3,0.6,0.9], 'FaceAlpha', 0.5) ;
if size(datamat,2)>3
ha2 = area([datamat(:,2) datamat(:,end-1)-datamat(:,2)],'linestyle','none');
set(ha2(1), 'FaceColor', 'none');
set(ha2(2), 'FaceColor', [0.25,0.3,0.8], 'FaceAlpha', 0.2) ;
output = plot(datamat(:,3), 'Color', [0.25,0.3,0.8],'linewidth',1);
else
output = plot(datamat(:,2),'Color', [0.25,0.3,0.8],'linewidth',1);
end
ha3 = plot(zeros(size(datamat,1),1),'k','linewidth',0.5);% ADDED
xticks(xlabel)
xticklabels(cellstr(num2str(xlabel')))
end
  2 Comments
Adam Danz
Adam Danz on 15 Nov 2020
Edited: Adam Danz on 15 Nov 2020
Glad I could help. Lesson learned: specify object handles when creating the legend.
It's also a good idea to use the DisplayName property to define legend strings (see this answer).

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!