How do I plot multiple ,different sized arrays on one scatter plot and get the legend to match with the specified colors?

4 views (last 30 days)
I have 3 different data sets with varying xy array sizes (i.e. x1,y1,x2,y2,x3,y3) and I want to create a scatter plot with different symbols and colors on the same plot. I have managed to do this using the hold on command. The code is as follows:
figure
scatter(Shed_Rg,Shed,'b','o');
hold on
scatter(Uncertain_Rg,Uncertain,'k','.');
hold on
scatter(Attached_Rg,Attached,'g','x');
This works for plotting the points however when I create a legend, the colors of all the symbols in the legend are only produced in the last color I selected (in this case it would be green).

Answers (1)

Star Strider
Star Strider on 14 Jul 2017
Create handles to each scatter call, and then use them as arguments to your legend call:
figure
h1 = scatter(Shed_Rg,Shed,'b','o');
hold on
h2 = scatter(Uncertain_Rg,Uncertain,'k','.');
hold on
h3 = scatter(Attached_Rg,Attached,'g','x');
legend([h1,h2,h3], 'Shed', 'Uncertain', 'Attached')
The legend entries should be appropriate for each set.
  2 Comments
Randall  Berdon
Randall Berdon on 14 Jul 2017
Hi Star,
I cut and pasted your code however, the proposed solution has not seemed to work. Thanks for the attempt.
-Randall
Star Strider
Star Strider on 14 Jul 2017
It works for me:
Shed_Rg = rand(10,1);
Shed = rand(10,1);
Uncertain_Rg = rand(10,1)+1;
Uncertain = rand(10,1)+1;
Attached_Rg = rand(10,1)+2;
Attached = rand(10,1)+2;
figure
h1 = scatter(Shed_Rg,Shed,'b','o');
hold on
h2 = scatter(Uncertain_Rg,Uncertain,'k','.');
hold on
h3 = scatter(Attached_Rg,Attached,'g','x');
legend([h1,h2,h3], 'Shed', 'Uncertain', 'Attached')

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!