last legend on a subplot not plotting

Has anyone had this issue: when doing a figure with subplots and legends in each one, the last legend does not appear? It doesn't matter if there are 2 subplots or 10 and I don't recall if this was always the case or a new problem. I'm running R2012a. I've attached an image of what I'm talking about - in my code, legend is there for subplot(313) just like the other two and when I run that segment of code alone (not as a subplot), the legend appears. Any suggestions about how to fix this? Thanks!

 Accepted Answer

You didn’t post your code, but legend can take the handle of the particular axes object as its first argument. See if the technique in Specify Axes for Legend solves your problem.

4 Comments

Thanks for the suggestion. I followed the guidance in the link and it still didn't work. But I think the issue is coming from any additional figure elements after the last subplot. For example,
random = rand(100,3);
figure
ax1 = subplot(121)
plot(random(:,1),random(:,2),'b*')
hold on
plot(random(:,1),random(:,3),'r*')
legend(ax1, 'first','second')
ax2 = subplot(122)
plot(random(:,1),random(:,2)*2,'b*')
hold on
plot(random(:,1),random(:,3)*2,'r*')
legend(ax2, 'first','second')
suptitle('Test')
If you run everything up to suptitle, the second legend is there. Then it disappears after you run that last line. The same thing happens I place a text box outside of the axes. It's a bit strange, yes? (I got suptitle from the Exchange and haven't had any trouble with it before. I may have never wanted to put a legend in the last subplot though before now...)
I added hold off for each subplot, added my own version of ‘suptitle’ (the text call, whose coordinates are relative to the second subplot, since I prefer to use my own when the situation requires it), and both legends displayed correctly:
random = rand(100,3);
figure
ax1 = subplot(121)
plot(random(:,1),random(:,2),'b*')
hold on
plot(random(:,1),random(:,3),'r*')
hold off
legend(ax1, 'first','second')
ax2 = subplot(122)
plot(random(:,1),random(:,2)*2,'b*')
hold on
plot(random(:,1),random(:,3)*2,'r*')
hold off
legend(ax2, 'first','second')
text(-0.25, 2.1, 'Test','FontSize',14, 'FontWeight','bold')
ah, that helps! Thanks!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!