在 Matlab 中绘制误差线

Draw error bars in Matlab

我在 MATLAB 中创建了一个包含五个点的示例散点图,如下所示:

x = linspace(0,pi,5);
y = cos(x);
scatter(x,y);

在我的例子中,每个点的 y 值应在定义如下的预定义范围内:

y_limits = {[0.9 1.1], [0.6 0.8], [-0.1 0.1], [-0.8 -0.6], [-1.1 -0.9]};

因此,例如 x = 01y 值应在 [0.9 1.1].

范围内

我想在同一个地块中很好地画出五个垂直边界,也许是通过

我想得到一些比我在这种图形表示方面更有经验的人的建议或示例代码。

使用 line 命令创建线条。

for i = 1:length(x)
line([x(i) x(i)], [y_limits{i}]);
end

可以使用 patchfill 完成填充区域。对限制进行一些重新排序是必要的,以便给定的顺序遵循围绕要填充的区域的路径。一个不错的技巧是在这些填充区域上使用 alpha 命令来创建透明度。

hold on    
y_corners = reshape([y_limits{:}], 2, length(x)).'; %make an array
y_corners = [y_corners(:,1); flipud(y_corners(:,2))]; %corners follow a path around the shape
fill([x fliplr(x)], y_corners, 'blue');
alpha(0.5);

您可以使用 errorbar function

在一行中完成此操作
% Your example variables
x = linspace(0,pi,5)';
y = cos(x);
y_limits = [0.9, 1.1; 0.6, 0.8; -0.1, 0.1; -0.8, -0.6; -1.1, -0.9];

% Plot
errorbar(x, y, y - y_limits(:,1), y_limits(:,2) - y, 'x');
% Format: (x, y, negative error, positive error, point style)

结果:


编辑,调用时可以设置绘图的线条属性errorbar。例如,您可以使用更大的蓝色圆圈标记和更粗的红色误差线 使用:

errorbar(x, y, y - y_limits(:,1), y_limits(:,2) - y, 'o', 'MarkerSize', 2, 'MarkerFaceColor', 'b', 'MarkerEdgeColor', 'b', 'Color', 'r', 'LineWidth', 1);

请注意,对于这些图像,我正在使用 grid on 添加网格。第二个结果: