首页 > 解决方案 > MATLAB:使用“填充”功能时如何保持填充椭圆的纵横比?

问题描述

我在 xy 图上绘制实心圆和椭圆。椭圆来自 2x2 张量数据。x 方向和 y 方向的单位完全不同,具体取决于我正在绘制的数据类型。我希望在绘图上的某个 (x,y) 位置绘制一个椭圆,但我希望无论 x 和 y 轴单位如何,都可以保持绘制椭圆的纵横比。请注意,这axis equal不是一个选项,因为 x 和 y 比例非常不同。如果我尝试这样做axis equal,只会使情节变得非常小。

下面是一个简单的例子。在此示例中,第一个椭圆始终是一个完美的圆形,以供参考以查看图形如何扭曲它。任何帮助表示赞赏。

x = 100*[1 2 3 4]; %x direction is several orders of magnitude larger than y direction
y = [1 2 3 4]; %y direction
data = randn(4,1); %data to fill ellipse (irrelevant to the question)

nrot = 36; %Number of points on each ellipse

for i = 1:4
    %Elements of 2x2 tensor to make the ellipse
    r1 = randn; r2 = randn; r3 = randn; r4 = randn;

    for irot=1:nrot %Loop to get ellipse points

        rot_ang = (irot-1)*360/(nrot-1);
        v = [cosd(rot_ang),sind(rot_ang)]; %Rotating vector components

        if i == 1 %Ensure that the first ellipse is a perfect circle
            r1 = 0; r4 = 0; r3 = r2;
        end

        plot_vec = [r1 r2; r3 r4]*v';

        %x component of ellipse to plot
        ex(irot) = plot_vec(1);

        %y component of ellipse to plot
        ey(irot) = plot_vec(2);  
    end 

    %Plot the ellipse at the x-y location
    xp = x(i)+ex;
    yp = y(i)+ey;

    fill(xp,yp,data(i)); hold on %Plot ellipses filled with "data".


end

%"Axis equal" does not work in this case
%axis equal

标签: matlabmatlab-figureaxisfillellipse

解决方案


听起来您希望椭圆显示的数据纵横比为 1:1,即使轴的数据纵横比不是。一种选择是首先为轴选择所需的数据纵横比,然后在平移和绘制椭圆之前相应地缩放椭圆的 y 值:

x = 100*[1 2 3 4];
y = [1 2 3 4];
aspectRatio = 100;  % Choose an aspect ratio of 100
data = randn(4, 1);
nrot = 36;

for i = 1:4

  r1 = randn; r2 = randn; r3 = randn; r4 = randn;

  for irot = 1:nrot

    rot_ang = (irot-1)*360/(nrot-1);
    v = [cosd(rot_ang), sind(rot_ang)];

    if i == 1
      r1 = 0; r4 = 0; r3 = r2;
    end

    plot_vec = [r1 r2; r3 r4]*v';
    ex(irot) = plot_vec(1);
    ey(irot) = plot_vec(2);

  end

  xp = x(i)+ex;
  yp = y(i)+ey./aspectRatio;  % Scale ellipse y data by aspect ratio

  fill(xp, yp, data(i));
  hold on;
  daspect(gca, [aspectRatio 1 1]);  % Set aspect ratio of axes

end

这是结果图:

在此处输入图像描述

椭圆很小,但如果你放大你会看到它们看起来有正确的纵横比(即第一个看起来像一个圆圈)。


推荐阅读