Creating legend for scatter plot

5 views (last 30 days)
Sepp on 24 Feb 2018
Edited: Chris Angeloni on 25 Mar 2020
I have created a scatter plot in the following way:
arousal = [1, 9, 2, 5, 6, 8, 3, 2];
correctness = [1, 0, 1, 1, 1, 0, 0, 0];
type = {'type1', 'type1', 'type3', 'type2', 'type3', 'type1', 'type2', 'type1'};
plot(arousal, 'k');
hold on;
for i = 1:length(arousal)
switch type{i}
case 'type1'
color = 'r';
case 'type2'
color = 'g';
case 'type3'
color = 'b';
if correctness(i)
marker = 'o';
scatter(i, arousal(i), 90, color, marker, 'filled');
marker = 'o';
scatter(i, arousal(i), 90, color, marker, 'LineWidth', 2);
I'm using three different colors for the markers. The markers can either be filled or not.
Now I would like to create a legend containing the three different colors as well as explaining filled and not filled markers. For red color it should be written "type1" in the legend, for green color "type2" and for blue color "type3". Moreover, for a filled circle it should be written "correct" and for not filled "incorrect". The filled and not filled circles could for example drawn in black in the legend.
How can this be done?

Accepted Answer

Walter Roberson
Walter Roberson on 24 Feb 2018
Use logical indexing to make one scatter() call each to plot all of the cases of each possibility. Then you can naturally legend() those.
Alternately, after you are done with the plotting, use plot(nan,nan) or line(nan,nan) once for each color and marker and fill style, and record the handles of each, and legend() that set of handles. Because of the nan coordinates those lines will not be drawn, but because they exist they can be legend()'d
The third possibility is that as you run through the plotting, each time that you detect that you have plotted a combination that you have not plotted before, record the handle of the scatter() -- so any one combination will be recorded only once. Then afterwards, legend() the recorded handles.
A fourth possibility is to record all of the scatter handles, and then afterwards post-process getting the attributes of each, and unique() on the combination of attributes with the two-output version of unique. The second output will give you indices into the handles to select to legend()
  1 Comment
Chris Angeloni
Chris Angeloni on 25 Mar 2020
Edited: Chris Angeloni on 25 Mar 2020
These are great solutions, but shame on Matlab... these all feel like work arounds for functionality that should be much more intuitive...

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!