我有两组点,用蓝色星星和红点绘制它们.然后我用voronoi(X,Y)函数绘制两组的Voronoi图.我想指定每个单元格的颜色取决于它的网站属于哪个集合.我通过这种方式使用补丁功能几乎完成了这个:
[v,c]=voronoin(D);
for p=1:TheNumberOfSets
r=rand()/2+0.5; % random gray color
col=[r r r];
for s=1:PointsInSet(p)
l=l+1;
patch(v(c{l},1),v(c{l},2),col); % color
axis([0 10 0 10]);
end
end
WhereD是集合点的坐标,TheNumberOfSets显示我们有多少集合(在这个特定部分我们只有2集),col指定一个随机灰色,PointsInSet指定我们在每个集合中有多少点和l用于枚举Voronoi图的单元格.
现在我的问题(正如你所看到的!)是关于无界细胞的.这段代码只是改变有界单元格的颜色,我想在轴框的范围内(即图像中可以看到的框)用指定集合的颜色对无界单元格进行着色.
有什么建议吗?
最佳答案 您的示例实际上为无界单元格创建了修补对象,但由于它们包含具有表示无界边缘的Inf值的顶点,因此不会显示它们.您需要用有限顶点替换这些顶点才能完成补丁.
由voronoi生成的用于绘制无界单元边的顶点对于此目的是有用的.您可以在绘制voronoi图时获取这些:
h = voronoi(D);
v1 = shiftdim(reshape([h(2).XData;h(2).YData],2,3,[]),2); % Arranged one edge per row, one vertex per slice in the third dimension
最后绘制了无界边,因此您可以通过计算c中的无界单元来隔离这些边:
nUnbounded = sum(cellfun(@(ic)ismember(1,ic),c));
v1Unbounded = v1(end-(nUnbounded-1):end,:,:);
这些边的第一个列出的顶点是单元的有限顶点.由于浮点错误,这些并不总是与voronoin返回的坐标完全匹配,因此通过查找与pdist2的最小成对距离来识别这些编号的顶点对应:
[~,iBounded] = min(pdist2(v,v1Unbounded(:,:,1))); % Index of the bounded vertex
vUnbounded = v1Unbounded(:,:,2); % Displayed coordinate of the unbounded end of the cell edge
要在这些坐标中替换,您可以替换补丁(v(c {l},1),v(c {l},2),col);以下内容:
cPatch = c{l}; % List of vertex indices
vPatch = v(cPatch,:); % Vertex coordinates which may contain Inf
idx = find(cPatch==1); % Check if cell has unbounded edges
if idx
cPatch = circshift(cPatch,-idx); % Move the 1 to the end of the list of vertex indices
vPatch = [vPatch(1:idx-1,:)
vUnbounded(iBounded == cPatch(end-1),:)
vUnbounded(iBounded == cPatch(1),:)
vPatch(idx+1:end,:)]; % Replace Inf values at idx with coordinates from the unbounded edges that meet the two adjacent finite vertices
end
patch(vPatch(:,1),vPatch(:,2),col);