密度散点(density scatter)相比较于普通的散点图而言,以不同的颜色显示样本的密度大小。
- 加载数据(load外部数据)
- 计算散点密度,并分配颜色
- 计算线性拟合关系
- 绘制散点图
clear all;
clc;
filen = 'F:\testdata.mat';
colormap_n = 'F:\mycolor_map.mat';
%% 加载数据和colormap
load(filen);
load(colormap_n);
x = x6;
y = y6;
%%
rmse = num2str(roundn(sqrt(mean((y-x).^2)),-2));
p=polyfit(x,y,1);%
yfit=polyval(p,x);%求拟合后的y值;
mdl = fitlm(x,y);%求一元线性拟合的参数
[~,pp] = corrcoef(x,y);
r2 = num2str(roundn(mdl.Rsquared.Ordinary,-2));%即一元线性拟合的R平方
r = num2str(roundn(sqrt(mdl.Rsquared.Ordinary),-2));
a = num2str(roundn(p(1),-2));%即y=ax+b中的a值
b = num2str(roundn(p(2),-2));%即y=ax+b中的b值
if pp<0.05
Formu = ['y=',a,'x+',b,sprintf('\n'),'R^2=',r2,sprintf('\n'),'p<0.05'];%这里字符串是拟合公式和R平方
else
Formu = ['y=',a,'x+',b,sprintf('\n'),'R^2=',r2,sprintf('\n'),'p>0.05'];
end
c = ksdensity([x,y], [x,y]);
minc = min(c);
maxc = max(c);
cc = c;
[nl,ns] = size(c);
for i=1:nl
cc(i,:) = (c(i,:)-minc)/(maxc-minc);
end
h = scatter(x, y, 5, cc,'filled');
xlim([0,3000]);%x轴的范围
ylim([-1,1]); %y轴的范围
colormap(mycolor1);
grid on
box on
h1 = lsline;
set(h1(1),'color','k');
set(h1(1),'LineWidth',1.5);hold off;
hold on;
h=colorbar;
set(h,'YTick',[0,0.25,0.5,0.75,1]); %色标值范围及显示间隔
set(h,'YTickLabel',{'0','0.25','0.5','0.75','1.0'}) %具体刻度赋值
set(get(h,'Title'),'string','point density');
hold on;
xlabel('x轴标题','fontsize',13);
ylabel('correlation coefficients','fontsize',13);
hold on;
title('图标题','fontsize',13);