Matlab读取Excel数据并绘制三维散点图
Matlab读取Excel数据并绘制三维散点图
本文介绍如何使用Matlab读取存储在Excel文件不同sheet中的数据,并根据这些数据绘制三维散点图。代码中还包含了连接相同x和y坐标的点以及添加文本标签的功能。
代码示例
% 设置文件名和sheet名
file = '混合表.xls';
sheet1 = 'Sheet1';
sheet2 = 'Sheet2';
% 读取第一个sheet内的坐标信息
[num1, txt1, raw1] = xlsread(file, sheet1);
x1 = num1(:, 1);
y1 = num1(:, 2);
z1 = num1(:, 3);
names1 = txt1(:, 4); % 假设第四列是点的名称
% 读取第二个sheet内的坐标信息
[num2, txt2, raw2] = xlsread(file, sheet2);
x2 = num2(:, 1);
y2 = num2(:, 2);
z2 = num2(:, 3);
names2 = txt2(:, 4); % 假设第四列是点的名称
% 绘制三维散点图
figure;
scatter3(x1, y1, z1, 'r', 'filled');
hold on;
scatter3(x2, y2, z2, 'b', 'filled');
xlabel('X');
ylabel('Y');
zlabel('Z');
title('网络空间负载配置图');
legend(sheet1, sheet2);
grid on;
% 绘制相同x和y坐标的点之间的虚线连接
for i = 1:length(x1)
idx = find(x2 == x1(i) & y2 == y1(i));
if ~isempty(idx)
plot3([x1(i), x2(idx)], [y1(i), y2(idx)], [z1(i), z2(idx)], '--k');
end
end
% 添加文本标签
for i = 1:length(x1)
text(x1(i), y1(i), z1(i), names1{i}, 'Color', 'red', 'FontSize', 8);
end
for i = 1:length(x2)
text(x2(i), y2(i), z2(i), names2{i}, 'Color', 'blue', 'FontSize', 8);
end
解决坐标点和标签不对应的问题
如果绘制的图形中坐标点和标签不对应,可能是因为数据读取时使用了错误的列索引。请确保以下代码行中的索引与Excel文件中数据的实际列对应:
x1 = num1(:, 1);
y1 = num1(:, 2);
z1 = num1(:, 3);
names1 = txt1(:, 4);
x2 = num2(:, 1);
y2 = num2(:, 2);
z2 = num2(:, 3);
names2 = txt2(:, 4);
例如,如果坐标信息在Excel文件的第2、3和4列,而点的名称在第1列,则应将索引修改为:
x1 = num1(:, 2); % 第2列为x坐标
y1 = num1(:, 3); % 第3列为y坐标
z1 = num1(:, 4); % 第4列为z坐标
names1 = txt1(:, 1); % 第1列为点的名称
x2 = num2(:, 2); % 第2列为x坐标
y2 = num2(:, 3); % 第3列为y坐标
z2 = num2(:, 4); % 第4列为z坐标
names2 = txt2(:, 1); % 第1列为点的名称
根据你的实际数据列顺序和对应关系进行适当的调整,以确保坐标点和标签在图形上正确对应。
原文地址: https://www.cveoy.top/t/topic/sNh 著作权归作者所有。请勿转载和采集!