【问题标题】:Plotting a grouped 2 dimensional vector in MATLAB在 MATLAB 中绘制分组的二维向量
【发布时间】:2010-05-11 16:43:37
【问题描述】:

我正在尝试绘制二维向量图(2D 图)。但我不希望所有数据点在图上都具有相同的颜色。每个数据点对应一个组。我想为每组数据点设置不同的颜色。

class=[1 3 2 5 2 5 1 3 3 4 2 2 2]

表示每个数据点属于哪个组

X=[x1,y1;x2,y2;x3,y3;.....] 

这些数据点的数量与类向量中的元素数量相同。

现在我想根据颜色绘制这些。

【问题讨论】:

    标签: matlab plot


    【解决方案1】:

    您可以使用SCATTER 轻松绘制不同颜色的数据。顺便说一句,我同意@gnovice 使用classID 而不是class

    scatter(X(:,1),X(:,2),6,classID); %# the 6 sets the size of the marker.
    

    编辑

    如果要显示图例,则必须使用 @yuk's 或 @gnovice 解决方案。

    GSCATTER

    %# plot data and capture handles to the points
    hh=gscatter(randn(100,1),randn(100,1),randi(3,100,1),[],[],[],'on');
    %# hh has an entry for each of the colored groups. Set the DisplayName property of each of them
    set(hh(1),'DisplayName','some group')
    

    情节

    %# create some data
    X = randn(100,2);
    classID = randi(2,100,1);
    classNames = {'some group','some other group'}; %# one name per class
    colors = hsv(2); %# use the hsv color map, have a color per class
    
    %# open a figure and plot
    figure
    hold on
    for i=1:2 %# there are two classes
    id = classID == i;
    plot(X(id,1),X(id,2),'.','Color',colors(i,:),'DisplayName',classNames{i})
    end
    legend('show')
    

    如果您有统计工具箱,您可能还想看看grouped data

    【讨论】:

    • 有趣的是,您可以使用与 classID 相同长度的向量作为第三个参数来按符号大小区分类别。尝试scatter(X(:,1),X(:,2),classID*1000,'r.') 绘制气泡图。
    • 谢谢,我也找到了这个,但你的更好:gscatter(m(:,2),m(:,1),classID,'brgyckm','o')
    • 有没有办法得到这个图例?
    • @Hossein:不是为了分散,而是为了其他两个。
    【解决方案2】:

    首先,由于CLASS 是一个内置函数,我将把你的向量命名为classID

    然后,对于classID 中的每个值,您可以执行以下操作:

    index = (classID == 1);            %# Logical index of where classID is 1
    plot(X(index,1),X(index,2),'r.');  %# Plot all classID 1 values as a red dot
    hold on;                           %# Add to the existing plot
    

    【讨论】:

    • 谢谢,我也找到了这个,但你的更好:gscatter(m(:,2),m(:,1),classID,'brgyckm','o')。并感谢您对“类”的评论。
    【解决方案3】:

    还可以查看 Statistics Toolbox 中的 GSCATTER 函数。您可以为每个组指定一次颜色、大小和符号。

    gscatter(X(:,1),X(:,2),classID,'bgrcm');
    

    或者只是

    gscatter(X(:,1),X(:,2),classID); %# groups by color by default
    

    【讨论】:

      猜你喜欢
      • 2021-07-24
      • 2011-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-04
      • 1970-01-01
      • 2012-08-17
      • 2017-01-27
      相关资源
      最近更新 更多