Legend command not working when plotting figure
Show older comments
I am trying to plot 2 lines with shared axes. The code I'm using is below. Everything works as intended other than the legend command. It doesn't matter where in the code I put it, it doesn't work. In certain positions it messes up the rest of the code too (e.g. it will disable logarithmic axes).
figure('units','normalized','outerposition',[0 0 1 1])
pbaspect([1 1 1])
title('AE-8 Electron Energy Spectra', 'FontSize', 18)
hold on
plot(ElectronEnergy, ElectronDifFlue, 'LineWidth', 1.5)
plot(ElectronEnergy, ElectronSolMinDifFlue, 'LineWidth', 1.5)
ylabel('Differential Fluence (cm^{-2} MeV^{-1})', 'FontSize', 18)
set(gca, 'FontSize', 16, 'YScale', 'log')
axis([0.01 10 1000000 1000000000000000])
grid on
xlabel('Energy (MeV)', 'FontSize', 18)
set(gca, 'XScale', 'log')
legend('Solar Maximum', 'Solar Minimum', 16)
Any advice is appreciated. Thanks!
Accepted Answer
More Answers (1)
Try something like
figure
pbaspect([1 1 1])
loglog(ElectronEnergy(:), [ElectronDifFlue(:) ElectronSolMinDifFlue(:)], 'LineWidth', 1.5)
xlim([0.01 10 1E6 1E15])
grid on
hAx=gca;
hAx.FontSize=16;
title('AE-8 Electron Energy Spectra')
xlabel('Energy (MeV)')
ylabel('Differential Fluence (cm^{-2} MeV^{-1})')
legend('Solar Maximum', 'Solar Minimum')
Simplify first...|hold on| first is often not a good idea; that bypasses quite a bit of the behind-the-scenes preparations for figures done by default; wait until the first line is drawn and want to add additional data onto the same axes. But, all the basic plot functions handle multiple columns(*) as independent vectors; put the two together as shown. Then, save some code/typing by using the loglog function to do the axes scale at first...then do the annotation stuff later on after the lines are drawn. This doesn't really matter all that much other than for code organization.
Lastly, my guess is that the problem with legend is one that there simply isn't sufficient room when you try to use such a large font size -- I left the "16" in, but even that may be larger than what there is room to put on a default figure size...sometimes there just simply isn't enough real estate available and one has to accept that.
(*) The (:) ensures are column vectors to catenate; if your data are already column vectors can dispense with.
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!