1

我有一组 (矩阵 Nx1)和这些点的(矩阵 Nx1)。我想绘制这些点(没问题,我这样做:)plot(points, groups, 'o');,但我想为每个组设置唯一的颜色。我怎样才能做到这一点?现在我只有两组(1,2)。

4

3 回答 3

3

使用逻辑索引来选择你想要的点

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');
于 2011-07-21T12:34:25.580 回答
2

给定一些随机数据:

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

以下是一些更一般的建议:

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')

scatter_lines

如果您有权访问统计工具箱,则有一个函数可以在一次调用中简化上述所有操作:

gscatter(points, groups, groups)

最后,在这种情况下,显示箱线图会更合适:

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

箱形图

于 2011-07-21T14:33:05.807 回答
0

假设组的数量是先验已知的:

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

findgroups将为您提供条件成立的所有指数。您将 的输出用作和的每个可能值的子find向量。pointsgroupsgroups

当您用于plot绘制多个 xy 组合时,它会为每个组合使用不同的颜色。

或者,您可以明确选择每种颜色:

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

最后,有一种方法可以让 plot 自动循环显示颜色,这样您就可以plot在不指定颜色的情况下调用,但该方法让我无法理解。

于 2011-07-21T12:16:20.527 回答