-
Notifications
You must be signed in to change notification settings - Fork 0
/
mT_addLegend.m
71 lines (51 loc) · 1.83 KB
/
mT_addLegend.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
function mT_addLegend(figHandle, legendLabels, legendColours, legTitle, ...
fontSize, lineWidth)
% Add a legend to a plot/subplot by drawing new invisible lines.
% INPUT
% figHandle: Figure to add legend to
% legendLabels: cell array of str. Gives the labels of the series to add
% to the legend.
% legendColours: cell array of 3-element vectors. Gives the colours for the
% series described in legendLabels.
% legTitle: empty or str. Provide legend title, if desired.
% fontSize: scalar. Font size for legend. May be empty to use default.
% lineWidth: scalar. Line width for legend. May be empty to use default.
assert(length(legendLabels) == length(legendColours))
if ~exist('fontSize', 'var')
fontSize = 10;
end
if ~exist('lineWidth', 'var')
lineWidth = 1;
end
% Find shape of subplots
subplotWidth = findNumSubplots(figHandle, 1);
subplotHeight = findNumSubplots(figHandle, 2);
subplotIdx = mT_createSubplotIdxArray(subplotWidth, subplotHeight);
set(0, 'currentFigure', figHandle)
subplotNum = subplotIdx(ceil(subplotHeight/2), end);
mT_getAxisWithoutOverwrite(figHandle, subplotHeight, subplotWidth, ...
subplotNum);
hold on
for iLabel = 1 : length(legendLabels)
legendLine(iLabel) = ...
errorbar(NaN, NaN, NaN, NaN, 'Color', legendColours{iLabel});
end
legObj = legend(legendLine, legendLabels{:});
legend boxoff
legObj.FontSize = fontSize;
legObj.LineWidth = lineWidth;
legObj.ItemTokenSize(1) = 15;
legObj.Location = 'southeast';
if exist('title', 'var') && ~isempty(legTitle)
title(legObj, legTitle)
end
end
function numSubplots = findNumSubplots(figHandle, axis)
positions = [];
currentAxes = findobj(get(figHandle, 'Children'), 'type', 'axes', ...
'-depth', 1);
for iC = 1 : length(currentAxes)
positions = [positions, currentAxes(iC).Position(axis)];
end
numSubplots = length(unique(positions));
end