Add refline (hline) to the legend

15 views (last 30 days)
Christian
Christian on 6 Apr 2017
Hello everybody,
I have a simple (?) question. I have been searching on the web for a while now, but wasn't able to find a satisfying solution. I have several subplots where I added different reflines with the following code:
subplot(2,1,1)
hold on
plot(x1, y1,'--r')
plot(x2, y2,'r','LineWidth',1.5)
hline = refline([0 threshlod_1]);
hline.Color = 'k';
hline.LineStyle = ':';
hline = refline([0 threshold_2]);
hline.Color = 'k';
hline.LineStyle = ':';
legend('data1','data2')
Now I want to add these reflines to the legends of the subplots.
-> legend('data1','data2','threshold_1','threshold_2')
Do you have any idea how this can be done?
Thank you in advance
cheers
Christian

Answers (2)

Thorsten
Thorsten on 6 Apr 2017
Use handles:
hold on
h(1) = plot(x1, y1,'--r')
h(2) = plot(x2, y2,'r','LineWidth',1.5)
h(3) = refline([0 threshlod_1]);
h(3).Color = 'k';
h(3).LineStyle = ':';
h(4) = refline([0 threshold_2]);
h(4).Color = 'k';
h(4).LineStyle = ':';
legend(h, 'data1','data2','threshold_1','threshold_2')
  1 Comment
Christian
Christian on 6 Apr 2017
That Code gives me the following error:
Structure assignment to non-structure object.
Error in my_script(line 681)
h(3).Color = 'k';

Sign in to comment.


Samuel Anyaso-Samuel
Samuel Anyaso-Samuel on 5 Mar 2018
This should work.
subplot(2,1,1)
hold on
plot(x1, y1,'--r')
plot(x2, y2,'r','LineWidth',1.5)
a = refline([0 threshlod_1]);
a.Color = 'k';
a.LineStyle = ':';
a.DisplayName = 'line a'
b = refline([0 threshold_2]);
b.Color = 'k';
b.LineStyle = ':';
b.DisplayName = 'line b'
legend('show')

Community Treasure Hunt

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

Start Hunting!