好看的阴影误差图

测试代码: 

clear,clc;
x = 0:10:500; 
y_true =  30*sind(x) + x/10; 
sigma = 3; 
y_measured = y_true + sigma*randn(size(x)); 
plot(x,y_true,'k','linewidth',2)
hold on
plot(x,y_measured,'color',[0.0118 0.2078 0])
ylabel( 'Y轴');xlabel('X轴');
% 绘制不确定性阴影区间
errorshade(x,y_measured,sigma,[1 0.4 0.7]) 
legend('真实值','测量值 \pm\sigma = 3 mV ','location','northwest')
legend box off 
axis tight 
title('好看的阴影误差图')

 自定义的errorshade函数如下:

function h = errorshade(x,y,sigma,color,varargin)
%errorshade绘制阴影区域以指示高斯不确定性。
%通过生成指定颜色的RGB图像并设置透明度来作图
%% 语法规则
%  errorshade(x,y,sigma,color) 
%  errorshade(...,'resolution',res) 
%  errorshade(...,'average',N)
%  h = errorshade(...)
% 
%% 简介
%
% %errorshade(x,y,sigma ,color)以高斯阴影区域为中心绘制
% x,y:为数据行。 
%sigma:表示阴影的一个标准偏差
% color:为rgb值的三元素向量。

%% 举例
%数据
% x = 0:10:500; 
% y_true =  30*sind(x) + x/10; 
% sigma = 3; 
% y_measured = y_true + sigma*randn(size(x)); 
% plot(x,y_true,'k','linewidth',2)
% hold on
% plot(x,y_measured,'color',[0.0118 0.2078 0])
% ylabel 'some values in mV'
% 
% % 绘制不确定性阴影区间
% errorshade(x,y_measured,sigma,[0.0824 0.6902 0.1020]) 
% legend('true value','measured value \pm\sigma = 3 mV uncertainty','location','northwest')
% legend boxoff 
% axis tight  
%% Error checks: 

narginchk(4,inf) 
assert(numel(color)==3,'输入错误: 颜色必须是三元素向量.')
assert(numel(x)==numel(y),'输入错误::x 和 y 维度必须相等') 
assert(isscalar(sigma)==1,'输入错误: sigma必须是标量.') 

%% Input parsing 

tmp = strncmpi(varargin,'resolution',3); 
if any(tmp)
   res = varargin{find(tmp)+1}; 
   if isscalar(res) 
      res = [res res]; 
   else
      assert(numel(res)==2,'输入错误: 分辨率必须是标量或二元素向量.') 
   end
else
   res = 2500*[1 1]; 
end

tmp = strncmpi(varargin,'average',2); 
if any(tmp)
   avg = varargin{find(tmp)+1}; 
   assert(isscalar(avg)==1,'输入错误: 移动平均距离必须为标量.')
   y = imfilter(y(:),fspecial('average',[avg 1]),'replicate');
end

buffer = 3*sigma; % This is the padding to add around all measurements in the vertical dimension. 

%% 限制范围: 

% 制作一个与数据缓冲区的尺寸相对应的网格: 
[X,Y] = meshgrid(linspace(min(x),max(x),res(1)),linspace(min(y)-buffer,max(y)+buffer,res(2))); 

% Find y locations along all x points of the grid
yi = interp1(x,y,linspace(min(x),max(x),res(1)));

% 正态分布: 
P = (1/sqrt(2*pi*sigma^2)) * exp(-(bsxfun(@minus,Y,yi)).^2/(2*sigma^2));

%每个点到yi的距离将用作透明度的量度:
Z = P-min(P(:));
Z = Z/max(Z(:)); 

%创建指定颜色的RGB图像: 
RGB = cat(3,color(1)*ones(size(Z)),color(2)*ones(size(Z)),color(3)*ones(size(Z))); 

% 绘制颜色的RGB图像: 
h = image(RGB,'xdata',X(1,:),'ydata',Y(:,1)); 
axis xy 

% 设置透明度: 
set(h,'alphadata',Z)

% 将渲染器设置为OpenGL,因为透明度仅适用于OpenGL: 
set(gcf,'renderer','OpenGL'); 

% 发送到底部: 
uistack(h,'bottom')

%% 清除: 
if nargout==0 
   clear h
end

end

 运行结果:

 

 

群资料 

posted on 2020-02-26 17:41  好玩的MATLAB  阅读(22)  评论(0编辑  收藏  举报  来源

导航