在之前的文章中,分享了Matlab密度散点图 的绘制方法**:**

进一步,假如我们需要计算、添加散点的拟合线,该怎么操作呢?
本期就来分享一下带回归趋势线的密度散点图的绘制方法,先来看一下成品效果:

特别提示:本期内容『数据+代码』已上传资源群中,加群的朋友请自行下载。有需要的朋友可以关注同名公号【阿昆的科研日常】,后台回复关键词【绘图桶】查看加入方式。
1. 数据准备
此部分主要是读取原始数据并初始化绘图参数,然后计算生成回归线参数(本文采用多项式回归)。
% 读取数据load data.mat% 初始化绘图参数data = [x,y];% 密度计算radius = 1.5; % 定义半径density_2D = density2D_KD(data(:,1:2),radius); % 2D平面密度% 回归趋势线生成xq = min(data(:,1)):0.1:max(data(:,1));p = polyfit(data(:,1),data(:,2),1);x1 = linspace(min(data(:,1)),max(data(:,1)),100);y1 = polyval(p,x1);
2. 颜色定义
作图不配色就好比做菜不放盐,总让人感觉少些味道。
但颜色搭配比较考验个人审美,需要多加尝试。
这里直接使用TheColor配色工具中的SCI权威配色库:
%% 颜色定义map = TheColor('sci',2064);map = flipud(map);

3. 带回归趋势线的密度散点图绘制
调用'scatter'与'plot'命令,绘制初始带回归趋势线的密度散点图。
scatter(data(:,1), data(:,2), 5, density_2D, 'filled')p1 = plot(x1,y1,'LineStyle',':','LineWidth',2,'Color','k');hTitle = title('Satellite-derived bathymetry');hXLabel = xlabel('ICESat-2 bathymetric points in depth (m)');hYLabel = ylabel('Estimated depth (m)');
4. 细节优化
为了插图的美观,将初始密度散点图赋上之前选择的颜色:
% 赋色colormap(map)colorbar
进一步,对坐标轴细节等进行美化:
% 坐标轴美化set(gca, 'Box', 'off', ... % 边框 'LineWidth',1,... % 线宽 'XGrid', 'on', 'YGrid', 'on', ... % 网格 'TickDir', 'out', 'TickLength', [.005 .005], ... % 刻度 'XMinorTick', 'off', 'YMinorTick', 'off', ... % 小刻度 'XColor', [.1 .1 .1], 'YColor', [.1 .1 .1],... % 坐标轴颜色 'XTick', 0:40:160,... % 坐标区刻度、范围 'XLim', [0 160],... 'YTick', 0:40:160,... 'YLim', [0 160])hLegend = legend(p1, ... 'Regression line',... 'Location', 'northwest'); set(gca, 'FontName', 'Arial', 'FontSize', 10)set([hLegend, hXLabel, hYLabel], 'FontSize', 11, 'FontName', 'Arial')set(hTitle, 'FontSize', 12, 'FontWeight' , 'bold')% 背景颜色set(gcf,'Color',[1 1 1])% 添加上、右框线xc = get(gca,'XColor');yc = get(gca,'YColor');unit = get(gca,'units');ax = axes( 'Units', unit,... 'Position',get(gca,'Position'),... 'XAxisLocation','top',... 'YAxisLocation','right',... 'Color','none',... 'XColor',xc,... 'YColor',yc);set(ax, 'linewidth',1,... 'XTick', [],... 'YTick', []);
设置完毕后,以期刊所需分辨率、格式输出图片。
%% 图片输出figW = figureWidth;figH = figureHeight;set(figureHandle,'PaperUnits',figureUnits);set(figureHandle,'PaperPosition',[0 0 figW figH]);fileout = 'test';print(figureHandle,[fileout,'.png'],'-r300','-dpng');

也可以尝试其它配色:




以上。