Matlab:更改图例中条目的顺序

Pat*_*ate 1 matlab legend legend-properties matlab-figure

我有一个图文件,我想改变条目的顺序(例如,将第一个条目作为第三个条目).我很久以前保存了这个Figure.fig所以我不确定我是否可以恢复原始代码.

在这里,我向您展示我的情节:

我的情节

我希望图例元素处于递减顺序(如图中所示),但由于错误,我的第二个条目是指错误的图(它表示"25年",但该图实际上是指最低趋势,相应的到了"9年"的趋势.

我可以直接从Matlab中的图的属性编辑器切换图例中条目的顺序吗?如果是,如何(我没有看到任何"订单"属性或类似)?否则有没有其他简单的方法来切换Legend中条目的顺序?

exc*_*aza 6

如果您的图形是在R2014b或更新版本中生成的,则可以使用未记录的'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');
Run Code Online (Sandbox Code Playgroud)

生产:

开始

然后你可以操纵:

neworder = [3, 1, 4, 2];
lh.PlotChildren = lh.PlotChildren(neworder);
Run Code Online (Sandbox Code Playgroud)

生产:

好极了

如果没有legend对象的句柄,则它是figure包含axes绘制数据的对象的对象的子对象.您可以legend使用以下findobj方法之一找到对象的句柄:

% Handle to figure object known
lg = findobj(figureobj, 'Type', 'legend');

% Handle to figure object unknown
lh = findobj(gcf, 'Type', 'legend');
Run Code Online (Sandbox Code Playgroud)

请注意,通常会将句柄返回到用户单击的最后一个数字,但情况并非总是如此.gcf


自我升级编辑:此方法包含在StackOverflow MATLAB社区在GitHub上维护的一组图例操作工具中.


Sue*_*ver 5

使用早于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));
Run Code Online (Sandbox Code Playgroud)

更新

要在从文件加载时正确处理,您可以获取所有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))
Run Code Online (Sandbox Code Playgroud)