On a few occasions, I have had an interesting figure I saved but I lost an access to its data. This example shows a trick how to achieve extract information from a figure.
The key functions are findobj and get. findobj returns a handler to an object given attributes or properties of the object, such as Type
or Color
, etc. Once a line object has been found, get can return any value held by properties. It turns out that the Line
objects hold all data in following properties: XData
, YData
, and ZData
; the last one is usually 0 unless a figure contains a 3D plot.
The following code creates an example figure that shows two lines a sin function and a threshold and a legend
t = (0:1/10:1-1/10)';
y = sin(2*pi*t);
plot(t,y);
hold on;
plot([0 0.9],[0 0], 'k-');
hold off;
legend({'sin' 'threshold'});
The first use of findobj returns two handlers to both lines:
findobj(gcf, 'Type', 'Line')
ans =
2x1 Line array:
Line (threshold)
Line (sin)
To narrow the result, findobj can also use combination of logical operators -and
, -or
and property names. For instance, I can find a line object whose DiplayName
is sin
and read its XData
and YData
.
lineh = findobj(gcf, 'Type', 'Line', '-and', 'DisplayName', 'sin');
xdata = get(lineh, 'XData');
ydata = get(lineh, 'YData');
and check if the data are equal.
isequal(t(:),xdata(:))
ans =
1
isequal(y(:),ydata(:))
ans =
1
Similarly, I can narrow my results by excluding the black line (threshold):
lineh = findobj(gcf, 'Type', 'Line', '-not', 'Color', 'k');
xdata = get(lineh, 'XData');
ydata = get(lineh, 'YData');
and last check confirms that data extracted from this figure are the same:
isequal(t(:),xdata(:))
ans =
1
isequal(y(:),ydata(:))
ans =
1