【问题标题】:matlab plot different colorsmatlab绘制不同的颜色
【发布时间】:2011-10-10 04:08:02
【问题描述】:

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

【问题讨论】:

  • “组”是什么意思?
  • 我的意思是我有例如 100 个点的 [0..10],如果点

标签: matlab colors plot points scatter


【解决方案1】:

假设组数是先验已知的:

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

find 将为您提供条件成立的groups 的所有索引。对于groups 的每个可能值,您使用find 的输出作为points 和groups 的子向量。

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

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

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

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

【讨论】:

  • 如果你设置了'hold all',每次你调用 plot 时它都会添加到同一个图中,但是会循环使用默认的颜色图和线条样式。
【解决方案2】:

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

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

【讨论】:

  • ok,如果点和组的维数是2怎么办?如何仅使用第一个 col 绘制绘图(points(ind),groups(ind),'o');
  • @Yekver:我不确定我是否明白你想要什么。您可以通过points(ind, 1) 索引第一列的所有行。如果要从矩阵的第一列创建索引向量,可以使用ind = (groups(:,1) == 1);
【解决方案3】:

给定一些随机数据:

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

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

gscatter(points, groups, groups)

最后,在这种情况下,显示Box plot会更合适:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多