How to put legend outside the chart?

87 views (last 30 days)
Hi,
I have problem with put legend outside the chart. The main problem is that the weekdays axis doesn't fit to chart.
This is my code:
ax1 = axes();
ax1.Box = 'on';
y=[0.34 0.34]
a=area([0 35],y, 'FaceColor', [0.9 0.9 0.9],'LineStyle','none');
hold on
b=area([180 323],y, 'FaceColor', [0.9 0.9 0.9],'LineStyle','none');
hold on
c=area([468 611],y, 'FaceColor', [0.9 0.9 0.9],'LineStyle','none');
hold on
d=area([756 899],y, 'FaceColor', [0.9 0.9 0.9],'LineStyle','none');
hold on
f=plot(x, jh2L1, x, jh2L2, x, jh2L3, x, oh2L1, x, oh2L2, x, oh2L3)
a.HandleVisibility = 'off';
b.HandleVisibility = 'off';
c.HandleVisibility = 'off';
d.HandleVisibility = 'off';
legend('L1-background (no-load)','L2-background (no-load)','L3-background (no-load)','L1-load condition','L2-load condition','L3-load condition', 'Location', 'Northeastoutside')
ax=gca
xticks([1 24:24:1008])
xticklabels({'18:10','22:00','02:00','06:00','10:00','14:00','18:00','22:00','02:00','06:00','10:00','14:00','18:00','22:00','02:00','06:00','10:00','14:00','18:00','22:00','02:00','06:00','10:00','14:00','18:00','22:00','02:00','06:00','10:00','14:00','18:00','22:00','02:00','06:00','10:00','14:00','18:00','22:00','02:00','06:00','10:00','14:00','18:00'})
xtickangle(-60)
%ylabel('2nd harmonic time-profile')
xlim([1,1008])
ylim([0,0.34])
ax2 = axes();
hold(ax2);
ax2.Position = ax1.Position;
ax2.Color = 'none';
ax2.XAxisLocation = 'top';
ax2.YAxis.Visible = 'off';
plot(NaT, NaN); % to make x-axis datetime
ax2.XLim = [datetime(2001, 3, 28) datetime(2001, 4, 4)]+hours(8);
ax2.XTick = [ax2.XLim(1) ax2.XTick];
drawnow;
%ax2.XAxis.TickLabelFormat = 'MMM dd';
ax2.XAxis.TickLabelFormat = 'eeee';

Accepted Answer

Ameer Hamza
Ameer Hamza on 29 Nov 2020
The Position property of ax2 gets changed later when you resize the figure window. It is better to use linkprop(). Change the line
ax2.Position = ax1.Position;
to
linkprop([ax1 ax2], 'Position')
  4 Comments
Ameer Hamza
Ameer Hamza on 29 Nov 2020
I am glad to be of help!

Sign in to comment.

More Answers (0)

Categories

Find more on Graphics Object Properties 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!