Creating legend for scatter plot

9 次查看(过去 30 天)
Hello
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';
end
if correctness(i)
marker = 'o';
scatter(i, arousal(i), 90, color, marker, 'filled');
else
marker = 'o';
scatter(i, arousal(i), 90, color, marker, 'LineWidth', 2);
end
end
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?

采纳的回答

Walter Roberson
Walter Roberson 2018-2-24
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 个评论
Chris Angeloni
Chris Angeloni 2020-3-25
编辑:Chris Angeloni 2020-3-25
These are great solutions, but shame on Matlab... these all feel like work arounds for functionality that should be much more intuitive...

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Scatter Plots 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by