MATLAB:使用“填充”功能时如何保持椭圆的长宽比?

时间:2019-02-13 19:14:40

标签: matlab matlab-figure axis fill ellipse

我在x-y图上绘制实心圆和椭圆。椭圆是从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

1 个答案:

答案 0 :(得分:2)

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

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
%matplotlib inline

out_file = "path_to_file/file.csv"
df = pd.read_csv(out_file)

time = df['date']
data = df['data']
ax1 = plt.subplot2grid((4,3),(0,0), colspan = 2, rowspan = 2) # Will be adding other plots
plt.plot(time, data)
plt.yticks(np.arange(1,5,1)) # Include classes 1-4 showing only 1 step changes
plt.gca().invert_yaxis() # Reverse y axis 
plt.ylabel('Trend', fontsize = 8, labelpad = 10)

这是结果图:

enter image description here

椭圆形很小,但是如果缩放,您会发现它们似乎具有正确的长宽比(即第一个看起来像一个圆)。