🕖上午好,题主!目前:🟢[在线]
📢参考通义千问、由郭老师整理提供!
📣今日诗号:死生契阔,与子成说。执子之手,与子偕老。
您遇到的问题是图例顺序与绘制箭头的顺序不一致导致的。在 MATLAB 中,legend
函数默认按照绘图的先后顺序关联图例标签。
以下是修正后的代码及解释:
% 示例数据
start_point = [0, 0, 0];
end_point1 = [1, 1, 1];
end_point2 = [-1, 1, -1];
end_point3 = [1, -1, -1];
% 绘制三维箭头
figure; hold on;
% 注意此处调整了绘制顺序,使得与图例顺序一致
h1 = quiver3(start_point(1), start_point(2), start_point(3), end_point1(1), end_point1(2), end_point1(3), 'Color', 'b', 'LineWidth', 5);
h2 = quiver3(start_point(1), start_point(2), start_point(3), end_point2(1), end_point2(2), end_point2(3), 'Color', 'r', 'LineWidth', 3);
h3 = quiver3(start_point(1), start_point(2), start_point(3), end_point3(1), end_point3(2), end_point3(3), 'Color', 'm', 'LineWidth', 1);
% 设置图例
legend([h1, h2, h3], 'S1', 'S2', 'S3', 'Location', 'northwest');
% 其他绘图设置
xlabel('X');
ylabel('Y');
zlabel('Z');
grid on;
view(3);
解释:
- 调整绘制顺序: 将绘制紫色箭头的代码
quiver3(..., 'Color', 'm', ...)
移到绘制红色箭头的代码 quiver3(..., 'Color', 'r', ...)
之前,确保绘制顺序与图例标签顺序一致。 - 将图形对象传递给
legend
函数: 将每个 quiver3
函数的返回值(图形句柄)保存到变量 h1
, h2
, h3
中,并将它们作为第一个参数传递给 legend
函数。这将确保图例标签与对应的图形对象正确关联。
通过以上修改,图例标签将与对应的箭头颜色和粗细正确匹配,并且紫色箭头的标签也将正常显示。