Reputation: 59
I have a code in matlab in which i'm plotting several 2d points, which belong in 16 classes, so i use 16 different colors. Is there any easy way to have a legend that denote the class name for each color?
Code looks something like this:
for i=1:length(data)
color = class_color(i);
plot(data(i,1),data(i,2),'*','Color',color);
hold on;
end
Upvotes: 0
Views: 746
Reputation: 1587
You could plot all the data points for a single class together with logical indexing.
Assuming you have the classes defined somewhere, say in class_number
which is the same length as data
, with entries ranging from 1
to 16
, and c_colors
, a cell array of length 16 with the colors corresponding to each class: then
for jj = 1:16
mask = (class_number==jj);
plot(data(mask,1),data(mask,2),'*','Color',c_colors{jj});
hold on
end
hold off
(Not tested).
Then you can store the names of the classes in a cell array and call legend
on that.
class_name{1} = 'Type a';
class_name{2} = 'Type b';
% etc, up to
class_name{15} = 'Type o';
class_name{16} = 'Type p';
legend(class_name);
Upvotes: 1
Reputation: 3791
That is a bad idea to use 16 colors to differentiate data points. Like colors will blend together. I suggest using different markers+colors. Four markers like '*'
, 'x'
, '+'
, '.'
, etc. and four colors for each marker. Then you can use legend('Class 1','Class 2', Class n')
. It should show each marker of the specific color. This will probably be the case when it is best to write out each line without loop and add %comments after each marker/color/class describing what it is, in case you have to come back to this code later. It is not really a solution you are asking for, but this is how I would do it.
Upvotes: 0