Adding more circles to the scatter plot legend

I am using the following code and want to create a legend where different colors correspond to different dosage.
Currently, all the points are marked as the same color in the legend (attached)
dpli_dris = [1,2,3,4]
hub_dris = [1,2,3,3.5]
dosage_order = [1,2,3,4]
dosage = ['1 mcg/kg/min';'3 mcg/kg/min';'4 mcg/kg/min';'6 mcg/kg/min'];
handle = figure;
s=scatter(dpli_dris,hub_dris,[],'b','filled','o','MarkerEdgeColor',[0 0 0])
hold on
s.AlphaData = dosage_order;
s.MarkerFaceAlpha = 'flat';
leg = legend(dosage,'Location','northeastoutside');
What can I do to fix the legend?
Thank you

Answers (1)

If you want different colors, call the scatter function seperately for each point. Currently, you are assigning the same color blue to all the 4 points in vectors dpli_dris & hub_dris using single scatter call.
dpli_dris = [1,2,3,4];
hub_dris = [1,2,3,3.5];
dosage_order = [1,2,3,4];
dosage = {'1 mcg/kg/min','3 mcg/kg/min','4 mcg/kg/min','6 mcg/kg/min'};
hold on
scatter(dpli_dris(1),hub_dris(1),'b','filled','o','MarkerEdgeColor',[0 0 0])
scatter(dpli_dris(2),hub_dris(2),'r','filled','o','MarkerEdgeColor',[0 0 0])
scatter(dpli_dris(3),hub_dris(3),'g','filled','o','MarkerEdgeColor',[0 0 0])
scatter(dpli_dris(4),hub_dris(4),'m','filled','o','MarkerEdgeColor',[0 0 0])
leg = legend(dosage,'Location','northwest'); grid

3 Comments

Alternate way is to call the scatter function inside the for loop as shown below
dpli_dris = [1,2,3,4];
hub_dris = [1,2,3,3.5];
dosage_order = [1,2,3,4];
dosage = {'1 mcg/kg/min','3 mcg/kg/min','4 mcg/kg/min','6 mcg/kg/min'};
colors = {'b','r','g','m'};
hold on
for k = 1:length(hub_dris)
scatter(dpli_dris(k),hub_dris(k),colors{k},'filled','o','MarkerEdgeColor',[0 0 0])
end
leg = legend(dosage,'Location','northwest'); grid
Yep. But I wanted to find a way to assign different transparency across the dosages instead of assigning a different color.
Use MarkerFaceAlpha as you did earlier but with a slight change
dpli_dris = [1,2,3,4];
hub_dris = [1,2,3,3.5];
dosage_order = [1,2,3,4];
dosage = {'1 mcg/kg/min','3 mcg/kg/min','4 mcg/kg/min','6 mcg/kg/min'};
% colors = {'b','r','g','m'};
Alpha = [0.2 0.4 0.6 0.8]
Alpha = 1×4
0.2000 0.4000 0.6000 0.8000
hold on
for k = 1:length(hub_dris)
scatter(dpli_dris(k),hub_dris(k),'b','filled','o','MarkerEdgeColor',[0 0 0],'MarkerFaceAlpha',Alpha(k))
end
leg = legend(dosage,'Location','northwest'); grid

Sign in to comment.

Products

Release

R2022b

Asked:

on 18 Jun 2023

Edited:

on 19 Jun 2023

Community Treasure Hunt

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

Start Hunting!