具有一个级别的多个 matlab 等高线图

multiple matlab contour plots with one level

我有一些来自 2 个类别的二维概率质量函数。我正在尝试绘制轮廓以将它们可视化(例如在它们的半高处,但并不重要)。

我不想用contourf直接绘图,因为我想控制填充颜色和不透明度。所以我使用 contourc 生成 xy 坐标,然后使用 fill 和这些 xy 坐标。

问题是 contourc 函数的 xy 坐标中有奇怪的数字,导致绘制以下奇怪的顶点。

起初我认为这是奇怪的 contourmatrix 格式,但我不认为是这样,因为我只要求 contourc 中的一个值。例如...

contourmatrix = contourc(x, y, Z, [val, val]);
h = fill(contourmatrix(1,:), contourmatrix(2,:), 'r');

有谁知道为什么 contourmatrix 中有这些奇怪的值,而我只要求一个轮廓?

更新:

当输入二维矩阵不是 'smooth' 时,我的问题似乎可能是 contourc 的故障模式。我的源数据是一大组 (x,y) 点。然后我创建了一个带有一些 hist2d 函数的二维矩阵。但是当这很嘈杂时,问题就被夸大了......

但是当我使用 2d 核密度函数生成更平滑的 2D 函数时,问题就减轻了...

完整的过程是 a)我有一组(x,y)点,它们从分布中形成样本 b) 我将其转换为 2D pmf c) 使用 contourc 创建一个轮廓矩阵 d) 使用 fill

绘图

您的图形故障是由于您使用 ContourMatrix 中的数据的方式造成的。即使您只指定一个 isolevel,这也会导致多个不同的填充区域。因此 ContourMatrix 可能包含多个形状的数据。


简单示例:

isolevel = 2 ;
[X,Y,Z] = peaks ;
[C,h] = contourf(X,Y,Z,[isolevel,isolevel]);

产生:


请注意,即使您只指定了一个要绘制的等值线,这也会产生 2 个面片(2 个形状)。每个都有自己的定义,但它们都嵌入在 ContourMatrix 中,因此如果要单独提取每个形状坐标,则必须对其进行解析。

为了证明这一点,如果我简单地将完整的等高线矩阵丢给patch函数(thefill函数将无论如何都要创建补丁对象,所以我更喜欢在实用时使用低级函数)。我得到了和你一样的故障线:

xc = X(1,:) ;
yc = Y(:,1) ;
c = contourc(xc,yc,Z,[isolevel,isolevel]);
hold on
hp = patch(c(1,1:end),c(2,1:end),'r','LineWidth',2) ;

产生与您相同类型的故障:


现在,如果您在不包括定义列的情况下正确提取每个形状坐标,您将获得正确的形状。下面的示例是一种提取和绘制每个形状以获取灵感的方法,但它们有很多不同的方法。您当然可以压缩代码很多,但为了清楚起见,我在这里详细介绍了操作。

关键是阅读并理解 ContourMatrix 是如何构建的。

parsed = false ;
iShape = 1 ;
while ~parsed
    %// get coordinates for each isolevel profile
    level   = c(1,1) ; %// current isolevel
    nPoints = c(2,1) ; %// number of coordinate points for this shape

    idx = 2:nPoints+1 ; %// prepare the column indices of this shape coordinates
    xp = c(1,idx) ;     %// retrieve shape x-values
    yp = c(2,idx) ;     %// retrieve shape y-values
    hp(iShape) = patch(xp,yp,'y','FaceAlpha',0.5) ; %// generate path object and save handle for future shape control.

    if size(c,2) > (nPoints+1)
        %// There is another shape to draw
        c(:,1:nPoints+1) = [] ; %// remove processed points from the contour matrix
        iShape = iShape+1 ;     %// increment shape counter
    else
       %// we are done => exit while loop
       parsed  = true ;
    end
end
grid on

这将产生: