## how to add 2 legends for 2 portions of one plot?

on 17 Jul 2019

### KSSV (view profile)

on 17 Jul 2019
For the code provided below, I have distinguished two sub-regions of one plot p1 as p1a (blue) and p1b (red). How do I give legends for p1a and p1b?
x1=dataset1(:,1);
y1=dataset1(:,2);
p1=plot(x1,y1,'Color','blue');
fontSize=15;
title('Fibreoptic sensor output (Volts) v/s distance (mm)', 'FontSize', fontSize);
grid on;
xlabel('distace between the sensor tip and the cantilever (mm)', 'FontSize', fontSize-5);
ylabel('Sensor output (Volts)', 'FontSize', fontSize-5);
legend on;
x1a=dataset1a(:,1);
y1a=dataset1a(:,2);
hold on
p1a=plot(x1a,y1a,'Color','blue')
hold on
x1b=dataset1b(:,1);
y1b=dataset1b(:,2);
hold on
p1b=plot(x1b,y1b,'Color','red')
hold on

R2017b

on 17 Jul 2019
Edited by KSSV

### KSSV (view profile)

on 17 Jul 2019

The following plot gives rise to two legends
plot(x,y,'b');
hold on;
plot(x1,y1,'r');
legend( 'on', 'off');
matlab automatically assigns the legends to the two plots.
The following is the format for adding legends to a figure.
legend('plot 1 legend', 'plot 2 legend');

### KSSV (view profile)

on 17 Jul 2019

th = 0:pi/100:2*pi ;
y = sin(th) ;
plot(th,y)
% set 1
th1 = th(th<=pi) ;
y1 = y(th<=pi) ;
% set 2
th2 = th(th>pi) ;
y2 = y(th>pi) ;
% plot
plot(th1,y1,'r')
hold on
plot(th2,y2,'b')
legend('Set1','Set2')