MATLAB Answers

How to initialize toggle line visibility as off?

2 views (last 30 days)
Hi,
I'm plotting graphs in an UIAxes, and I have used the following the following function (also see the attached .mlapp file) to enable toggling between data by using the legends. However, I cannot figure out how to initialize the legends as clicked at startup? Can anyone help?
function legendBDCB(app,~,evnt)
% This function uses the postion data from where the legend was
% clicked to toggle a line on/off
% First, get all of the lines
lines = app.UIAxes.Children;
% Next, create segments based off of the number of lines. Based on
% where the user clicked in the legend, we will assign that click
% location to a line. This call generates a grid of equally spaced
% ranges, with the number of ranges equaling the number of lines
click_locations = linspace(0,1,numel(lines)+1);
% Get corresponding bin based on the 2nd value of
% evnt.IntersectionPoint. This corresponds to the vertical distance
% within the legend, which we can use to identify what line
% (roughly) in the legend was clicked
line_num = discretize(evnt.IntersectionPoint(2),click_locations);
% Set the visiblility of the corresponding line 'off' or 'on'
relevant_line = lines(line_num);
if strcmp(relevant_line.Visible,'on')
relevant_line.Visible = 'off';
else
relevant_line.Visible = 'on';
end
end
This is the link for the code:

Accepted Answer

Shiva Kalyan Diwakaruni
Shiva Kalyan Diwakaruni on 4 May 2021
Hi,
You can open the LegendLineVisibilityApp.mlapp in code view and add a startupFcn in like below and give legendBDCB as callback handle to ButtonDownFcn
methods (Access = private)
% Code that executes after component creation
function startupFcn(app)
plot(app.UIAxes, magic(5));
l = legend(app.UIAxes);
[app.UIAxes.Children(:).Visible] = deal('off','off','off','off','off');
% Here, we set the ButtonDownFcn, in place of the ItemHitFcn
% which is disabled for UIFigures/App Designer
l.ButtonDownFcn = @app.legendBDCB;
end
end
Hope it helps.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!