Vertical lines in legend:

16 views (last 30 days)
Poe li
Poe li on 25 May 2014
Answered: dpb on 25 May 2014
Hi all,
I have a matlab file where I read an excel file in matlab. I want to draw vertical lines in different colors at certain points. All well. I have 4 lines which are called d and all have the same color (done like d= line(). Next i have vertical lines e which also have a different color. Now when I make my legend I have the following: hLegend = legend('SPL','BPF','Motor rotational frequency','12 Hz','Harmonics of rotational frequency','Harmonics of BPF');
Harmonics of rotational frequency and harmonics of BPF are each around 4 vertical lines in the same color. My legend then says that Harmonics of BPF have the same color of Harmonics of rotational frequency, so I'd have to define the line harmonics of rotational frequency multiple times which makes the legend not so nice. Anyone knows how I can put the 4 lines together in the legend? This would make it much easier! Thanks!
  2 Comments
dpb
dpb on 25 May 2014
Already answered your question at cs-sm w/ a demo...
Poe li
Poe li on 25 May 2014
I thought I had posted it already here too, but it seems I posted it somewhere else. As I'm new here, can you link me here? Posting it there was not my intention, and I thought I had posted it here and it didn't appear for some reason. Sorry for double posting this then, though I'd love to have a link. Thanks!

Sign in to comment.

Answers (1)

dpb
dpb on 25 May 2014
OK, here's the response from cs-sm...
> Simplest would be to make each group of lines a column in the xy array
> and then legend() should do the grouping automagically.
Here's a trivial example of what mean...
y=rand(200,1)-0.5; % just some data for to plot
plot(y), ylim([-1 1]) % plot it, make look a little prettier
Now generate a set of 20 lines in four groups as 2D array by columns xL is 20 randomly selected locations from the overall length of 200 First duplicate that list by 3 for first,second x of line and a space holder for the NaN between lines to not draw the line between. Then reshape to get the 4 columns and insert the NaN between...
xL=sort(reshape(repmat(randperm(200,20),3,1),15,[]));
xL(3:3:end,:)=nan;
yL is to match from the ylimits...
yL=repmat([-1 1 nan].',5,4);
Then just draw 'em and use legend()...
line(xL,yL)
legend('a','b','c','d')
Use whatever logic you have for building the lines by group but populate the array as shown above. This uses the automagic internal recycling of colors; if you want specific colors by group, save the line handles and use set() to modify as desired.

Community Treasure Hunt

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

Start Hunting!