从现有绘图中提取MATLAB图例字符串
我一直在尝试从先前创建的绘图中获取一些数据,但我一直在与图例作斗争。我正在使用Matlab2014b 如果我以前使用以下方法设置绘图:从现有绘图中提取MATLAB图例字符串,matlab,matlab-figure,Matlab,Matlab Figure,我一直在尝试从先前创建的绘图中获取一些数据,但我一直在与图例作斗争。我正在使用Matlab2014b 如果我以前使用以下方法设置绘图: h.fig = figure(); h.ax = axes(); hold all; h.line1 = plot(0:0.01:2*pi(), sin(0:0.01:2*pi())); h.line2 = plot(0:0.01:2*pi(), cos(0:0.01:2*pi())); h.xlab = xlabel('X'); h.ylab =
h.fig = figure();
h.ax = axes(); hold all;
h.line1 = plot(0:0.01:2*pi(), sin(0:0.01:2*pi()));
h.line2 = plot(0:0.01:2*pi(), cos(0:0.01:2*pi()));
h.xlab = xlabel('X');
h.ylab = ylabel('Y');
h.leg = legend('sin(x)', 'cos(x)');
然后,在没有可用的h
的情况下,我仍然可以检索x轴和y轴标签作为字符串:
xlab = get(get(gca, 'xlabel'), 'string');
ylab = get(get(gca, 'ylabel'), 'string');
然而,我似乎无法以类似的方式从图例中提取文本。我注意到:
fig_children = get(gcf, 'children');
将轴和图例显示为图形的子对象,但我似乎无法以与轴相同的方式访问它们:
ax = get(gca);
我可能误解了它的工作方式,但我找不到从先前制作的图例中提取字符串的方法?图例文本与线条关联,而不是与图例对象关联,因此:
ax_children = get(gca, 'children');
输出我正在绘制的线的线阵列:
ax_children =
2x1 Line array:
Line (cos(x))
Line (sin(x))
然后:
leg_strings = get(ax_children, 'displayname');
输出单元阵列:
leg_strings =
'cos(x)'
'sin(x)'
这正是我想要的。要获取图例句柄(假设图中只存在一个,否则必须对其进行排序),可以使用以下命令:
findobj(gcf,'type','Legend')
ans =
Legend (sin(x), cos(x)) with properties:
String: {'sin(x)' 'cos(x)'}
Location: 'northeast'
Orientation: 'vertical'
FontSize: 9
Position: [0.7226 0.8325 0.1589 0.0619]
Units: 'normalized'
然后图例条目作为单元格数组提供
简言之:
leg_strings = get(findobj(gcf,'type','Legend'),'String');