MATLAB:如何通过增加和减少颜色阴影来遮蔽绘图区域

MATLAB: How do I shade plot area with increasing and decreasing shades of a color

我想用一种颜色(黑色)绘制图形区域(x = 1:24y = -1:1),然后我想 decrease/increase 根据一天中的时间。所以,我有一个图,晚上背景是 'dark',白天背景是 'light',x 是一天中的几个小时,y 是一个数据值。我的日出时间是 6.8,日落时间是 22。然后我会在散点图上叠加数据。

我试过摆弄 patcharea 但没有成功。这是我从互联网上其他地方获得的一些代码,但我不确定如何继续:

% Define x, f(x), and M(x)
x = linspace(6.8, 22)';
f = sin(x)+cos(x);
M = x.^2;

% Define the vertices: the points at (x, f(x)) and (x, 0)
N = length(x);
verts = [x(:), f(:), x(:) zeros(N,1)];

% Define the faces to connect each adjacent f(x) and the corresponding points at y = 0.
q = (1:N-1)';
faces = [q, q+1, q+N+1, q+N];
p = patch('Faces', faces, 'Vertices', verts, 'FaceVertexCData', [M(:); M(:)], 'FaceColor', 'interp', 'EdgeColor', 'none')

所以我希望最终结果类似于下面的图像(注意淡淡的阴影 - 我希望渐变更强),但 x = 1:24y = -1:1.

由于您忽略了我将您的 MATLAB 代码的结果包含在您的问题中的请求,因此我不得不查看我的 crystal 球以确定您的“胡闹”导致了以下错误消息:

Error using patch

While setting the 'Vertices' property of Patch:

Value must be a 1x2 or 1x3 vector of numeric type

Error in X (line 13)

p = patch('Faces', faces, 'Vertices', verts, 'FaceVertexCData', [M(:); M(:)], 'FaceColor', 'interp', 'EdgeColor', 'none')

这可以通过在第 8 行垂直而不是水平连接顶点来解决:

verts = [x(:), f(:); x(:), zeros(N,1)];

这会产生以下图:

这当然不是你想要的

实际解决方案

您可以用 5 个矩形构建背景:

x = [0;
     6;    % 'First daylight'
     6.8;  % Full brightness
     22;   % Beginning of 'sunset'
     22.8; % Complete darkness
     24];

vertices = [repmat(x,2,1), [ones(size(x)); -1.*ones(size(x))]];
faces = [1:5; 2:6; 8:12; 7:11].';
color = repmat([0 0 0; % 'Night' color
                0 0 0;
                1 1 1; % 'Day' color
                1 1 1;
                0 0 0;
                0 0 0],2,1);
              
patch('Faces',faces, ...
      'Vertices',vertices, ...
      'FaceVertexCData',color, ...
      'FaceColor','interp', ...
      'EdgeColor','red');
xlim([0 24]);

通过将适当的 RGB 值分配给 FaceVertexCData 属性,您可以将 'night' 矩形的顶点设为黑色,将 'day' 矩形的顶点设为白色。 =22=]

'sunrise'/'sunset' 矩形的颜色然后通过将 FaceColor 属性 设置为 'interp'.[=22 在黑色和白色之间插值=]

EdgeColor 仅设置为 'red' 以说明背景的构建方式。将 属性 设置为 'interp' 以使线条消失。