开发者

matlab plot different colors

I h开发者_开发百科ave set of points (matrix Nx1) and groups for this points (matrix Nx1). I want to plot this points (there is no problem, I do this like this: plot(points, groups, 'o');), but I'd like to set unique color for each group. How can I do this? Now I have only two groups (1,2).


Use logical indexing to select the points you want

figure;
hold all; % keep old plots and cycle through colors

ind = (groups == 1); % select all points where groups is 1

% you can do all kind of logical selections here:
% ind = (groups < 5)

plot(points(ind), groups(ind), 'o');


Given some random data:

points = randn(100,1);
groups = randi([1 2],[100 1]);

Here are a few more general suggestions:

g = unique(groups);           %# unique group values 
clr = hsv(numel(g));          %# distinct colors from HSV colormap
h = zeros(numel(g),1);        %# store handles to lines
for i=1:numel(g)
    ind = (groups == g(i));   %# indices where group==k
    h(i,:) = line(points(ind), groups(ind), 'LineStyle','none', ...
        'Marker','.', 'MarkerSize',15, 'Color',clr(i,:));
end
legend(h, num2str(g,'%d'))
set(gca, 'YTick',g, 'YLim',[min(g)-0.5 max(g)+0.5], 'Box','on')
xlabel('Points') ylabel('Groups')

matlab plot different colors

If you have access to the Statistics Toolbox, there is a function that simplifies all of the above in one call:

gscatter(points, groups, groups)

Finally, in this case, it would be more suitable to display the Box plot:

labels = num2str(unique(groups),'Group %d');
boxplot(points,groups, 'Labels',labels)
ylabel('Points'), title('Distribution of points across groups')

matlab plot different colors


Assuming the number of groups is known a-priori:

plot(points(find(groups == 1)), groups(find(groups == 1)), points(find(groups == 2)), groups(find(groups == 2)));

find will give you all the indices of groups for which the condition holds. You use the output of find as a subvector of both points and groups for each possible value of groups.

When you use plot to plot more than one x-y combination, it uses a different color for each.

Alternatively, you could just choose each color explicitly:

hold on
plot(points(find(groups == 1)), groups(find(groups == 1)), 'r')
plot(points(find(groups == 2)), groups(find(groups == 2)), 'y')

Finally, there's a way to tell plot to cycle through the colors automatically, so that you can call plot without specifying a color, but the method eludes me.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜