How can I give a different legend for each element of a vector in a scatter plot?
Ältere Kommentare anzeigen
Hi! I'm a beginner at Matlab and I'm having trouble to assign legend to my data in plots. Let's say I have three samples named 'a', 'b', 'c' which have X values of A e y values of B.
A=[1:3]; B=[9:11];
(example: sample 'a' has a value of 1 in the X axis and 9 in the y axis)
I created a string C=['a,b,c'] for the legend, but when I plot them and insert legend I don't get what I mean. This is what I did:
scatter(A,B); legend(C); And this is what Matlab returned:

What I wanted was that each marker could be assigned a different legend, since they refer to different samples. When I created separated variables for each sample, I could do what I wanted, but I'm sure there might have a simpler way of doing it.
p.s.: This is just an example, my real data might have up to 130 samples!
Antworten (3)
Walter Roberson
am 27 Jul. 2015
You cannot do that with scatter() and legend() in a single scatter call. scatter() only creates a single graphics object per call.
If you want to label the object "near" the dot, then consider
scatter(A,B); text(A,B,{' a',' b',' c'})
Notice the two extra spaces I put before each letter: that is to move the letter away from the dot.
If you want to use legend then:
for K = 1 : length(A);scatter(A(K),B(K)); hold on; end; legend({'a','b','c'})
Star Strider
am 27 Jul. 2015
You have to plot the individual data (or groups of data) separately, and you need to use a cell array for the legend, since the square brackets [] concatenate string arrays:
A=[1:3]; B=[9:11];
C={'a', 'b', 'c'};
figure(1)
hold on
for k1 = 1:length(A)
scatter(A(k1),B(k1))
end
hold off
legend(C)
2 Kommentare
Rayza Rosa Tavares Rodrigues
am 28 Jul. 2015
Star Strider
am 28 Jul. 2015
My pleasure!
If my Answer solved your problem, please Accept it.
Azzi Abdelmalek
am 27 Jul. 2015
A=[1:3];
B=[9:11];
figure;
hold on
for k=1:numel(A)
scatter(A,B,'facecolor','b')
end
hold off
legend({'a','b','c'})
Kategorien
Mehr zu Legend finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!