Creating legend for scatter plot
7 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Sepp
el 24 de Feb. de 2018
Editada: Chris Angeloni
el 25 de Mzo. de 2020
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?
0 comentarios
Respuesta aceptada
Walter Roberson
el 24 de Feb. de 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 comentario
Chris Angeloni
el 25 de Mzo. de 2020
Editada: Chris Angeloni
el 25 de Mzo. de 2020
These are great solutions, but shame on Matlab... these all feel like work arounds for functionality that should be much more intuitive...
Más respuestas (0)
Ver también
Categorías
Más información sobre Legend en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!