This week, I'd like to highlight one of the new R2016a features that just came out a couple of weeks ago. There are so many exciting features, and the one I'll be talking about today is related to a Pick from a while ago on clickableLegend by 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)
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.
function action1(src,event) % This callback toggles the visibility of the line if strcmp(event.Peer.Visible,'on') % If current line is visible event.Peer.Visible = 'off'; % Set the visibility to 'off' else % Else event.Peer.Visible = 'on'; % Set the visibility to 'on' end
Refer to the ItemHitFcn property for the explanation of the event data structure.
Then, you assign the function to the ItemHitFcn property of the legend object.
hLeg = legend('Line 1','Line 2','Line 3','Line 4'); hLeg.ItemHitFcn = @action1;
Here is a different function that blinks the line that is clicked.
function action2(src,event) % This callback causes the line to "blink" for id = 1:3 % Repeat 3 times event.Peer.LineWidth = 3; % Set line width to 3 pause(0.2) % Pause 0.2 seconds event.Peer.LineWidth = 0.5; % Set line width to 0.5 pause(0.2) % Pause 0.2 seconds end
hLeg.ItemHitFcn = @action2;
Displaying Line Elsewhere
Here is another function that displays the line on a different set of axes.
function action3(src,event,hAx) % This callback displays the selected line on a different set of axes x = event.Peer.XData; % Get X data of interest y = event.Peer.YData; % Get Y data of interest plot(hAx,x,y,'Color',event.Peer.Color) % Plot data with the same color title(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','Line 3','Line 4'); hAx = subplot(2,1,2); hLeg.ItemHitFcn = @(src,event) action3(src,event,hAx);
Let us know what you think here.
To leave a comment, please click here to sign in to your MathWorks Account or create a new one.