【发布时间】: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;.....]
这些数据点的数量与类向量中的元素数量相同。
现在我想根据颜色绘制这些。
【问题讨论】:
我正在尝试绘制二维向量图(2D 图)。但我不希望所有数据点在图上都具有相同的颜色。每个数据点对应一个组。我想为每组数据点设置不同的颜色。
class=[1 3 2 5 2 5 1 3 3 4 2 2 2]
表示每个数据点属于哪个组
X=[x1,y1;x2,y2;x3,y3;.....]
这些数据点的数量与类向量中的元素数量相同。
现在我想根据颜色绘制这些。
【问题讨论】:
您可以使用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。
【讨论】:
scatter(X(:,1),X(:,2),classID*1000,'r.') 绘制气泡图。
首先,由于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
【讨论】:
还可以查看 Statistics Toolbox 中的 GSCATTER 函数。您可以为每个组指定一次颜色、大小和符号。
gscatter(X(:,1),X(:,2),classID,'bgrcm');
或者只是
gscatter(X(:,1),X(:,2),classID); %# groups by color by default
【讨论】: