首页 > 解决方案 > Border of a scatter plot in Matlab: constructing it and colouring it

问题描述

I would like your help to plot the border of a scatter in Matlab and fill it with a specified colour.

Let me firstly show you how the scatter looks like.

scatter(x,y)

enter image description here

Now, let me show you what I have tried to design the border.

k = boundary(x,y);
plot(x(k),y(k));

which produces this enter image description here

This is not what I want. Firstly, the scatter is nicely convex and I don't understand why boundary produces that weird shape. Secondly, I want to colour with blue inside the border.

Could you kindly advise on how to proceed? Also, when building the border I would prefer not to rely on the convexity of the scatter, because in some of my real examples the scatter is not convex.

标签: matlabplot

解决方案


边界

如果没有任何关于预期内容的信息,就没有简单的方法来获得非凸形状的边界。边界什么时候应该遵循凸包,什么时候应该偏离它?Matlab 函数boundary是通用的,可用于任意输入坐标。它有一个“收缩因子”参数s,可以在 0(凸包)和 1(高度非凸)之间调整,具体取决于预期结果。

% Make some x,y data with a missing corner
[x,y]=meshgrid(1:20);
sel=~(x>15 & y<=5);
x=x(sel);y=y(sel);

% Compute boundary with several values for s
k=boundary([x,y]);            %Default shrink factor : 0.5
k_convhull=boundary([x,y],0);
k_closest=boundary([x,y],1);

% Plot the boundary:
plot(x,y,'ok') %black circles
hold on
plot(x(k),y(k),'-r') %red line
plot(x(k_convhull),y(k_convhull),'-g') %green line
plot(x(k_closest),y(k_closest),'-b') %blue line

即使将“收缩因子”设置为 1,重入角仍然会有所削减。如果这不适合您,您将需要创建自己的函数来计算边界的坐标。

绘制曲面

您需要在那里使用补丁对象。

p=patch(x(k3),y(k3),[1 .8 .8]);
uistack(p,'bottom')

[1 .8 .8]是补丁表面的 RGB 颜色(浅粉色) uistack,是为了将补丁移到其他图形对象下方,因为它不透明。如果有的话,它仍然会覆盖轴网格。另一种选择是:

p=patch(x(k3),y(k3),[1 0 0],'FaceAlpha',.2);

在这里,补丁将是纯红色并绘制在其他对象的顶部,但通过 Alpha 通道设置了 80% 的透明度(0 是完全透明的,1 是纯色)。

请注意,补丁对象类有很多选项,除了像这样的基本用例之外,处理起来有些复杂。


推荐阅读