我有一个关于使用area
函数的问题; 或者可能需要另一个函数...
我从一个大型文本文件中创建了这个图:
绿色和蓝色代表两个不同的文件。我的目标是分别填充红线和每条运行之间的区域。我可以使用类似的想法创建一个面积图,但当我将它们绘制在同一张图上时,它们无法正确重叠。基本上,4个图将显示在一个图上。
希望这样能让您明白。
fill
与 fliplr
结合使用即可。x=0:0.01:2*pi; %#initialize x array
y1=sin(x); %#create first curve
y2=sin(x)+.5; %#create second curve
X=[x,fliplr(x)]; %#create continuous x value array for plotting
Y=[y1,fliplr(y2)]; %#create y values for out and then back
fill(X,Y,'b'); %#plot filled area
通过翻转x数组并将其与原始数组连接起来,您可以向外、向下、向后、然后向上关闭两个数组,形成一个完整的多边形。就我个人而言,我认为将填充函数进行包装既优雅又方便。
要在两个大小相等的行向量Y1
和Y2
之间进行填充,这两个向量共享支撑数组X
(并且颜色为C):
fill_between_lines = @(X,Y1,Y2,C) fill( [X fliplr(X)], [Y1 fliplr(Y2)], C );
您可以使用函数FILL来创建填充多边形以覆盖您绘制的部分。您需要按照想要在屏幕上堆叠的顺序绘制线条和多边形,从最底部开始。以下是一些示例数据的示例:
x = 1:100; %# X range
y1 = rand(1,100)+1.5; %# One set of data ranging from 1.5 to 2.5
y2 = rand(1,100)+0.5; %# Another set of data ranging from 0.5 to 1.5
baseLine = 0.2; %# Baseline value for filling under the curves
index = 30:70; %# Indices of points to fill under
plot(x,y1,'b'); %# Plot the first line
hold on; %# Add to the plot
h1 = fill(x(index([1 1:end end])),... %# Plot the first filled polygon
[baseLine y1(index) baseLine],...
'b','EdgeColor','none');
plot(x,y2,'g'); %# Plot the second line
h2 = fill(x(index([1 1:end end])),... %# Plot the second filled polygon
[baseLine y2(index) baseLine],...
'g','EdgeColor','none');
plot(x(index),baseLine.*ones(size(index)),'r'); %# Plot the red line
这里是生成的图:
你也可以通过修改坐标轴对象中 'Children'
属性 中句柄的顺序来改变图形中对象的堆叠顺序。例如,以下代码可以颠倒堆叠顺序,将绿色多边形隐藏在蓝色多边形后面:
kids = get(gca,'Children'); %# Get the child object handles
set(gca,'Children',flipud(kids)); %# Set them to the reverse order
如果你不确定要先叠放哪个多边形(即任意一个都可能是较小的多边形,并且你可能想将其放在顶部),那么你可以调整'FaceAlpha'
属性,使得其中一个或两个多边形呈现为部分透明,并显示在其下方的另一个多边形。例如,以下内容将使绿色多边形部分透明:
set(h2,'FaceAlpha',0.5);
您需要查看patch()函数,并在水平线的起始点和终止点中设置点:
x = 0:.1:2*pi;
y = sin(x)+rand(size(x))/2;
x2 = [0 x 2*pi];
y2 = [.1 y .1];
patch(x2, y2, [.8 .8 .1]);
如果您只想要数据的部分填充区域,您需要将x和y向量截断,仅包括您需要的点。
yb = [y1',fliplr(y2')]
。而不是yb = [y1',fliplr(y2)']
。 - webelo