'PlotChildren'
属性来操纵图例条目的顺序,而无需进行新的legend
调用。x = 1:10;
y1 = x;
y2 = 2*x;
y3 = 3*x;
y4 = x.^2;
plot(x, y1, x, y2, x, y3, x, y4);
lh = legend('y = x', 'y = 2*x', 'y = 3*x', 'y = x.^2');
产生:
然后您可以进行操作:
neworder = [3, 1, 4, 2];
lh.PlotChildren = lh.PlotChildren(neworder);
生产:
如果您没有指向 legend
对象的句柄,那么它是包含您的数据绘制在上面的figure
对象和axes
对象的子级。 您可以使用以下任一 findobj
方法找到指向您的 legend
对象的句柄:
% Handle to figure object known
lg = findobj(figureobj, 'Type', 'legend');
% Handle to figure object unknown
lh = findobj(gcf, 'Type', 'legend');
gcf
一般返回用户单击的最后一个图形的句柄,但这并不总是这样。
legend
,而使用一个未记录的函数吗? - user2261062如果使用比R2014b版本旧的MATLAB版本,可以通过为plot
指定一个输出来获取图形对象的句柄。然后,您可以在传递到legend
之前按照所需顺序重新排列句柄。
x = 1:10;
y1 = x;
y2 = 2*x;
y3 = 3*x;
y4 = x.^2;
hplots = plot(x, y1, x, y2, x, y3, x, y4);
labels = {'y = x', 'y = 2*x', 'y = 3*x', 'y = x.^2'};
% Indices specifying the order in which you want the legend entries to appear
neworder = [3 1 4 2];
legend(hplots(neworder), labels(neworder));
更新
为了正确处理从文件加载的情况,您可以获取所有轴的Children
来获取绘图对象,并获取当前图例以获取标签。然后,您可以按照上述方法重新排序它们。
load('filename.fig');
labels = get(legend(), 'String');
plots = flipud(get(gca, 'children'));
% Now re-create the legend
neworder = [3 1 4 2];
legend(plots(neworder), labels(neworder))
Legend
对象的未记录的PlotChildren
属性,但是您必须首先将AutoUpdate
属性设置为'off'
。hLegend = legend({'Group A', 'Group C', 'Group B'});
hLegend.AutoUpdate = 'off';
hLegend.PlotChildren = hLegend.PlotChildren([1,3,2]);
AutoUpdate
为 'off'
时,添加到坐标轴的新图形对象将不再自动添加或删除相应的图例项。根据我的经验和其他人在excaza的回答中的评论,看起来他们使用未记录的函数的解决方案可能在R2017a之后不再有效。
以下示例使用与excaza原始答案相同的示例图,但不需要未记录的功能,并且似乎在(至少)R2021a中有效。它利用了指定要向其添加图例标签的图形对象子集的能力。此功能似乎保留了您传递这些图形对象的顺序。
例如,
x = 1:10;
y1 = x;
y2 = 2*x;
y3 = 3*x;
y4 = x.^2;
plot(x, y1, x, y2, x, y3, x, y4);
labels = {'y = x', 'y = 2*x', 'y = 3*x', 'y = x.^2'};
legend(labels)
neworder = [3, 1, 4, 2];
ax = gca;
children = ax.Children;
legend(children(neworder), labels(neworder))
修改之前的图形生成。
请注意,与类似问题的另一个答案不同的是,这不需要显式返回图形句柄并跟踪它们。这些句柄只需使用ax.Children
从轴中检索即可。legend([p2, p1], ["line 2", "line 1"])
当您绘制时创建行对象的p1 = plot(...),结合使用uistack,您可以更改哪些对象位于顶部,然后重新排序图例以使其有意义。例如:
uistack(psave_d,'top') % Brings certain line to front
legend([psave_a, psave_b, psave_g, psave_c, psave_d, psave_e, psave_f, psave_pde], ["k_y=0.000001 W/m/K","k_y=0.0001 W/m/K","k_y=0.001 W/m/K","k_y=0.01 W/m/K","k_y=0.1 W/m/K","k_y=1 W/m/K","k_y=10 W/m/K","Isothermal PDE Numerical Model"])
如果有人需要更多的细节,我很乐意提供。干杯!