Having trouble getting legend to display properly
9 views (last 30 days)
Show older comments
So I'm basically trying to make 1 general legend for multiple subplots (they should all have same legend).
I know matlab doesn't let you change many of the features of the legend (spacing, etc.) so I've opted to make a 4x4 subplot but only plot my figures in the first three columns and reserve the last column for my legend.
Here is my code:
% to plot all individuals across trials in subplot
odortrial = 3;
trialn = 6;
G = figure
B = (1:1:odortrial)
tri = (1:1:trialn).';
% for plotting only in first 3 cols
A = 1:1:numel(d)
A(mod(A,4)==0) = nan;
CC = A(~isnan(A));
ind = CC.';
num = [num2str(tri)];
for ii = 3:length(d)
for t = 1:trialn
if d(ii).isdir == 1
Gsub(i) = subplot(row,col,ind(ii-3));
L(t) = plot(B, Q{ii,1}(t,:), 'DisplayName', num);
ylim([0,10]);
hold on
title(sprintf('Fly %s%d', d(ii).name));
end
end
end
% subplot(row,col,1)
% plot(B,Q{4,1}(1,:))
A = zeros(size(numel(d)));
for i = 3:length(d);
if d(i).isdir == 1 ;
A(:,i) = d(i).isdir;
end
end
leg = legend(gca,'show');
% leg.FontSize = 6;
title(leg,'Trial #');
hold on
newPosition = get(subplot(row,col,4),'Position')
% newPosition(2) = newPosition(2)*2
newUnits = 'normalized';
set(leg,'Position', newPosition);
What I end up with is a legend that is covered by a blank subplot. How can I get rid of this? (Looks like this).
0 Comments
Answers (2)
the cyclist
on 12 Sep 2019
One possibility is to set the 'Visible' property of those axes to 'off'. Here is a simpler example ...
figure
plot(magic(3))
legend
set(gca,'Visible','off')
0 Comments
Jon
on 12 Sep 2019
Edited: Jon
on 12 Sep 2019
You could also try putting a common legend on the bottom of the page. Here is an example of how to do that
x = 1:100;
y = rand(100,6,9);
tri = (1:1:trialn).';
fig = figure
ax = gca
for k = 1:size(y,3)
subplot(3,3,k)
plot(x,y(:,:,k))
end
% add a common legend
h = legend(num2str(tri),'Orientation','horizontal');
% relocate it to bottom of plot
p = get(h,'Position');
p(1) = 0.2; % normalized x position
p(2) = 0.005; % normalized y position
set(h,'Position',p,'Units','normalized')
Sorry the image of the plot looks a little wonky, but it should look OK on your screen.
See Also
Categories
Find more on Legend in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!