MATLAB: Legend Problem in Scatter Plotting

graphMATLABplottingscatter

[m,n] = size(y);
x1 = X(:,1);
x2 = X(:,2);
for j=1:1:n
for i=1:1:m
if y(i,j)==1
scatter(x1(i,j), x2(i,j), 20, y(i,j),'k', '+');
else
scatter(x1(i,j), x2(i,j), 10, y(i,j),'y', 'filled');
hold on;
end
end
end
legend("Admitted","Not Admitted");
X is a 300×2 matrix consisting random data and y is a 300×1 matrix consisting only 0 and 1. I want to plot a 2D scatter graph of x1 and x2. Based on the value of y i.e. 0 or 1 the marker of the plot will be changed. But both the legend showing the same marker. I dont want to use any other plotting function , rather want to stick to scatter. The plot is showing like:

Best Answer

See if this does what you want:
[m,n] = size(y);
x1 = X(:,1);
x2 = X(:,2);
for j=1:1:n
for i=1:1:m
if y(i,j)==1
hs1 = scatter(x1(i,j), x2(i,j), 20, y(i,j),'k', '+');
else
hs2 = scatter(x1(i,j), x2(i,j), 10, y(i,j),'y', 'filled');
hold on;
end
end
end
legend([hs1(1),hs2(1)],"Admitted","Not Admitted");
I obviously cannot test this with your data, so I am posting it as UNTESTED CODE.
.
Related Question