1. MATLAB 2D散点图基础入门
2D散点图是数据可视化中最基础也最常用的图表类型之一。在MATLAB中,使用scatter函数可以轻松创建专业的散点图。我们先来看一个最简单的例子:
matlab复制x = randn(100,1);
y = randn(100,1);
scatter(x,y)
这段代码生成了100个随机点的散点图。但要让散点图真正发挥价值,我们需要掌握更多细节。
1.1 散点图的基本参数
scatter函数最常用的参数包括:
- 前两个参数是x和y坐标向量
- 第三个参数控制点的大小
- 第四个参数控制点的颜色
- 第五个参数控制点的填充样式
例如:
matlab复制x = 1:10;
y = rand(1,10);
sz = linspace(10,100,10);
c = linspace(1,10,10);
scatter(x,y,sz,c,'filled')
这里我们创建了10个点,点的大小从10到100线性增加,颜色也从1到10变化,并且点被填充。
1.2 散点图的样式定制
MATLAB提供了丰富的选项来自定义散点图的外观:
matlab复制scatter(x,y,'MarkerFaceColor','r','MarkerEdgeColor','k','LineWidth',1.5)
这段代码设置了红色填充、黑色边框、1.5磅线宽的散点图。我们还可以使用RGB三元组来指定精确的颜色:
matlab复制myColor = [0.2 0.6 0.8];
scatter(x,y,[],myColor)
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 高级散点图技巧
2.1 气泡图实现
通过调整点的大小来反映第三个变量的值,可以创建气泡图:
matlab复制x = rand(50,1);
y = rand(50,1);
z = rand(50,1)*100; % 第三个变量
figure
bubblechart(x,y,z)
title('气泡图示例')
xlabel('X值')
ylabel('Y值')
bubblelegend('气泡大小表示Z值')
2.2 分类散点图
当数据包含分类变量时,可以使用gscatter函数:
matlab复制load fisheriris
gscatter(meas(:,1),meas(:,2),species,'rgb','osd')
xlabel('萼片长度')
ylabel('萼片宽度')
这个例子使用了著名的鸢尾花数据集,不同颜色和形状的点代表不同种类的花。
2.3 散点图矩阵
对于多变量数据,散点图矩阵(scatterplotmatrix)非常有用:
matlab复制load carsmall
vars = {'MPG','Acceleration','Displacement','Weight'};
figure
plotmatrix(dataset2table(carsmall{:,vars}))
3. 散点图的交互功能
3.1 数据提示功能
启用数据提示可以让用户交互式查看数据点的详细信息:
matlab复制scatter(rand(20,1),rand(20,1),'filled')
dcm = datacursormode(gcf);
set(dcm,'UpdateFcn',@myfunction)
function output_txt = myfunction(~,event_obj)
pos = get(event_obj,'Position');
output_txt = {['X: ',num2str(pos(1))],...
['Y: ',num2str(pos(2))]};
end
3.2 动态散点图
创建动态变化的散点图可以展示数据随时间的变化:
matlab复制theta = linspace(0,2*pi,50);
r = rand(1,50);
h = scatter(r.*cos(theta),r.*sin(theta),'filled');
for i = 1:100
r = rand(1,50);
set(h,'XData',r.*cos(theta),'YData',r.*sin(theta));
pause(0.1)
end
4. 散点图的优化与美化
4.1 提高散点图性能
当处理大量数据点时,性能可能成为问题。以下是一些优化技巧:
matlab复制% 方法1:使用plot代替scatter(当不需要不同大小/颜色时)
x = randn(1e5,1);
y = randn(1e5,1);
plot(x,y,'.')
% 方法2:降低alpha值
scatter(x,y,10,[0 0 1],'filled','MarkerFaceAlpha',0.1,'MarkerEdgeAlpha',0.1)
4.2 专业出版级散点图
为了创建适合出版的散点图,需要注意以下细节:
matlab复制x = randn(100,1);
y = x + randn(100,1)*0.5;
figure('Color','white')
scatter(x,y,75,[0.2 0.4 0.6],'filled','MarkerEdgeColor','k','LineWidth',0.5)
set(gca,'FontSize',12,'FontName','Arial','Box','on','LineWidth',1)
xlabel('X变量','FontSize',14)
ylabel('Y变量','FontSize',14)
title('专业级散点图示例','FontSize',16)
grid on
set(gcf,'Position',[100 100 600 400])
exportgraphics(gcf,'scatter_high_quality.png','Resolution',300)
4.3 添加回归线和置信区间
在散点图上添加回归线可以更好地展示数据趋势:
matlab复制x = 1:10;
y = x + randn(1,10);
scatter(x,y,'filled')
hold on
[p,S] = polyfit(x,y,1);
[yfit,dy] = polyconf(p,x,S,'predopt','curve');
plot(x,yfit,'r-','LineWidth',2)
plot(x,yfit-dy,'r--',x,yfit+dy,'r--')
hold off
5. 散点图的常见问题解决
5.1 重叠点问题
当数据点密集时,点会重叠在一起难以分辨。解决方法包括:
- 使用半透明点:
matlab复制scatter(x,y,20,'filled','MarkerFaceAlpha',0.3)
- 使用抖动(jitter)技术:
matlab复制x_jittered = x + randn(size(x))*0.1;
scatter(x_jittered,y)
- 使用hexbin图替代:
matlab复制hexscatter(x,y,'res',20)
5.2 大数据集可视化
对于超过10万个数据点的散点图,传统方法会很慢。替代方案:
matlab复制% 方法1:随机采样
idx = randperm(length(x),10000);
scatter(x(idx),y(idx))
% 方法2:使用scatterhist
scatterhist(x,y,'Kernel','on','Location','NorthEast',...
'Direction','out','Color','k','Marker','.')
% 方法3:使用数据分箱
histogram2(x,y,'DisplayStyle','tile','ShowEmptyBins','on')
5.3 颜色映射问题
当使用颜色表示第三个变量时,常见问题包括:
- 颜色映射不清晰:
matlab复制c = rand(100,1)*100;
scatter(x,y,[],c,'filled')
colormap(jet)
colorbar
- 非线性颜色映射:
matlab复制c = exp(randn(100,1));
scatter(x,y,[],log(c),'filled')
colormap(parula)
colorbar
6. 散点图的进阶应用
6.1 三维散点图
虽然本文主要讨论2D散点图,但了解3D散点图也很有价值:
matlab复制[x,y,z] = sphere(16);
X = [x(:)*.5 x(:)*.75 x(:)];
Y = [y(:)*.5 y(:)*.75 y(:)];
Z = [z(:)*.5 z(:)*.75 z(:)];
S = repmat([1 .75 .5]*10,numel(x),1);
C = repmat([1 2 3],numel(x),1);
scatter3(X(:),Y(:),Z(:),S(:),C(:),'filled')
view(40,35)
6.2 散点图动画
创建散点图动画可以展示数据变化过程:
matlab复制theta = linspace(0,2*pi,50);
h = scatter(cos(theta),sin(theta),'filled');
for t = 0:0.1:10
x = cos(theta + t);
y = sin(theta + t) + 0.1*randn(size(theta));
set(h,'XData',x,'YData',y);
drawnow
end
6.3 地理散点图
对于地理数据,可以使用geoscatter函数:
matlab复制lat = 40 + 5*randn(100,1);
lon = -100 + 10*randn(100,1);
sz = 100*rand(100,1);
c = rand(100,1);
figure
geoscatter(lat,lon,sz,c,'filled')
geobasemap('streets')
7. 散点图与其他图表的组合
7.1 散点图与线图组合
matlab复制x = 1:10;
y1 = rand(1,10);
y2 = y1 + randn(1,10)*0.2;
scatter(x,y1,100,'b','filled')
hold on
plot(x,y2,'r-','LineWidth',2)
hold off
legend('数据点','趋势线')
7.2 散点图与误差条组合
matlab复制x = 1:5;
y = [2 3 5 4 6];
err = [0.5 0.3 0.8 0.2 0.6];
errorbar(x,y,err,'o','MarkerSize',10,...
'MarkerEdgeColor','red','MarkerFaceColor','red')
7.3 散点图与直方图组合
matlab复制x = randn(1000,1);
y = x + randn(1000,1);
figure
scatterhist(x,y,'Kernel','on','Location','NorthEast',...
'Direction','out','Color','k','Marker','.')
8. MATLAB散点图的导出与分享
8.1 导出高质量图片
matlab复制scatter(rand(50,1),rand(50,1),'filled')
exportgraphics(gcf,'scatter.png','Resolution',300)
支持格式包括PNG、JPEG、TIFF、PDF等。
8.2 创建交互式HTML
matlab复制fig = figure;
scatter(rand(50,1),rand(50,1),'filled')
filename = 'scatter_plot.html';
websave(filename,'https://www.mathworks.com/matlabcentral/mlc-downloads/downloads/...')
8.3 在App Designer中使用散点图
matlab复制% 在App Designer中添加坐标区组件
% 然后在回调函数中添加:
app.UIAxes.NextPlot = 'replace';
scatter(app.UIAxes,rand(50,1),rand(50,1),'filled')
9. 散点图的实际应用案例
9.1 金融数据分析
matlab复制load stockreturns
x = stocks(:,1);
y = stocks(:,2);
scatter(x,y,'filled')
hold on
plot(xlsread('fund.xls'),'r-')
hold off
xlabel('市场回报')
ylabel('个股回报')
title('资本资产定价模型分析')
9.2 科学实验数据可视化
matlab复制load reaction
scatter(reactants(:,1),rate,[],catalyst,'filled')
xlabel('反应物浓度')
ylabel('反应速率')
title('催化剂对反应速率的影响')
9.3 机器学习数据探索
matlab复制load fisheriris
features = meas(:,1:2);
species = categorical(species);
gscatter(features(:,1),features(:,2),species,'rgb','osd')
xlabel('萼片长度 (cm)')
ylabel('萼片宽度 (cm)')
title('鸢尾花数据集分类')
10. 散点图的最佳实践与技巧
- 始终添加轴标签和单位
- 考虑使用对数刻度当数据跨度大时
- 为彩色散点图添加颜色条说明
- 避免使用太多颜色类别(一般不超过7种)
- 对于分类数据,结合形状和颜色区分
- 当点很多时,使用半透明或小点
- 考虑添加参考线(如y=x线)
- 在出版物中使用矢量格式(PDF/EPS)
- 保持一致的风格贯穿所有图表
- 考虑目标受众调整图表复杂度
matlab复制% 示例:专业风格的散点图
x = randn(100,1);
y = x + randn(100,1)*0.5;
figure('Color','w','Position',[100 100 600 400])
scatter(x,y,50,[0.2 0.4 0.8],'filled','MarkerEdgeColor','k',...
'LineWidth',0.5,'MarkerFaceAlpha',0.7)
hold on
plot([-3 3],[-3 3],'k--') % 参考线
hold off
set(gca,'FontSize',11,'LineWidth',1,'Box','on','TickDir','out')
xlabel('测量值','FontSize',12)
ylabel('预测值','FontSize',12)
title('测量值与预测值比较','FontSize',14)
grid on
colorbar('Ticks',[],'Title','密度')
