MATLAB: Scatter plot with a color variation based on a third vector

caxisgrouped scattergscatterscatter

I have three variables (Return, Risk, Supply) where I would like to present them on a scatter plot as the attached. I would like to plot them based on the two variables (Return and Risk) and I would like to color them based on the third variable (supply). Now I want to keep the color varying and I would like to make any value of the supply that is higher than 4800 blue and any value that is less than 4000 red? Anyway to help. I would like to add the colorbar and legend next to that. I have attached my data and code as below
pointsize = 100;
figure
scatter(Return,Risk, pointsize,Supply, 'filled')
ylim([0 35])
% colormap(jet(25))
% caxis([0 max([z1(:);z2(:)])])
colorbar;
title('Efficient Frontier Focusing on Fields [1,2,8] Producing on Year 1');
xlabel('Expected Risk, B$') % x-axis label
ylabel('Expected NPV, B$') % y-axis label

Best Answer

Use gscatter() (grouped scatter)
%Define thesholds

thresholds = [4000, 4800];
pointsize = 30;
group = ones(length(Supply),1).*2;
group(Supply < thresholds(1)) = 1;
group(Supply > thresholds(2)) = 3;
groupColors = [0 0 1; 0 0 0; 1 0 0];
figure()
gscatter(Return,Risk,group,groupColors,'.',pointsize,'filled')
ylim([0 35])
title('Efficient Frontier Focusing on Fields [1,2,8] Producing on Year 1');
xlabel('Expected Risk, B$') % x-axis label

ylabel('Expected NPV, B$') % y-axis label

% Create colorbar

colormap(groupColors)
chb = colorbar();
caxis([0,1])
set(chb,'Ticks',0.1667:0.3334:1,'TickLabels',{'sup<4000', 'between', 'sup>4800'})
Or use scatter() and define color of each plot
%Define thesholds
thresholds = [4000, 4800];
% Assign color
colorID = zeros(length(Supply),3); % default is black
colorID(Supply < thresholds(1),3) = 1; %blue
colorID(Supply > thresholds(2),1) = 1; %red
% your code, slightly adapted
pointsize = 100;
figure
scatter(Return,Risk,pointsize,colorID,'filled');
ylim([0 35])
title('Efficient Frontier Focusing on Fields [1,2,8] Producing on Year 1');
xlabel('Expected Risk, B$') % x-axis label
ylabel('Expected NPV, B$') % y-axis label
% Create colorbar
colormap([0 0 1;0 0 0;1 0 0])
chb = colorbar();
caxis([0,1])
set(chb,'Ticks',0.1667:0.3334:1,'TickLabels',{'sup<4000', '', 'sup>4800'})