File Exchange Pick of the Week

Our best user submissions

Interactive Legend in R2016a

Jiro's pick this week is a feature that allows you tocreate interactive legends using callbacks.

This week, I'd like to highlight one of the newR2016a featuresthat just came out a couple of weeks ago. There are so many excitingfeatures, and the one I'll be talking about today is related to aPickfrom a while ago onclickableLegendby one of our ex-MathWorkers,Ameya. Ameya's entry allowed you to create an interactive legend for turning on and off particular lines.

With R2016a, you can specify custom actions that get executed when one clicks on a legend item. Let's try with the following data set.

x = linspace(0,10); y1 = sin(x); y2 = cos(x); y3 = sin(x) + cos(x); y4 = sin(x) .* cos(x); plot(x,y1,x,y2,x,y3,x,y4)

Toggle Visibility

To use this new feature, you first create a function that defines the specific action you want to perform. For example, the following function toggles the visibility of the line.

functionaction1(src,event)% This callback toggles the visibility of the lineifstrcmp(event.Peer.Visible,'on')% If current line is visibleevent.Peer.Visible ='off';% Set the visibility to 'off'else% Elseevent.Peer.Visible ='on';% Set the visibility to 'on'end

Refer to theItemHitFcnproperty for the explanation of theeventdata structure.

Then, you assign the function to theItemHitFcnproperty of thelegendobject.

hLeg = legend('Line 1','Line 2',的第3行','Line 4'); hLeg.ItemHitFcn = @action1;

Blinking Line

这是一个提单的不同功能inks the line that is clicked.

functionaction2(src,event)% This callback causes the line to "blink"forid = 1:3% Repeat 3 timesevent.Peer.LineWidth = 3;% Set line width to 3pause(0.2)% Pause 0.2 secondsevent.Peer.LineWidth = 0.5;% Set line width to 0.5pause(0.2)% Pause 0.2 secondsend
hLeg.ItemHitFcn = @action2;

Displaying Line Elsewhere

Here is another function that displays the line on a different set of axes.

functionaction3(src,event,hAx)% This callback displays the selected line on a different set of axesx = event.Peer.XData;% Get X data of interesty = event.Peer.YData;% Get Y data of interestplot(hAx,x,y,'Color',event.Peer.Color)% Plot data with the same colortitle(hAx,event.Peer.DisplayName)% Set the title to the line name
subplot(2,1,1) plot(x,y1,x,y2,x,y3,x,y4) hLeg = legend('Line 1','Line 2',的第3行','Line 4'); hAx = subplot(2,1,2); hLeg.ItemHitFcn = @(src,event) action3(src,event,hAx);

Comments

Let us know what you thinkhere.




Published with MATLAB® R2016a

|
  • print
  • send email

Comments

To leave a comment, please clickhereto sign in to your MathWorks Account or create a new one.