How can I use a plot legend to toggle an element's visibility?
Show older comments
Hi,
I am trying to plot multiple items on the same plot, but I would like to implement a quick method to hide or show a single item, e.g. by clicking on it on the plot legend. I have tried with the clickable legend (as described here: https://www.mathworks.com/matlabcentral/fileexchange/21799-clickablelegend-interactive-highlighting-of-data-in-figures), but this functionality seems to be unsupported in more recent MATLAB releases. I have also tried to include a callback function (as in this example: https://blogs.mathworks.com/pick/2016/03/25/interactive-legend-in-r2016a/), again with no results.
Thanks in advance for your help
7 Comments
dpb
on 23 Apr 2023
alessandro marino
on 24 Apr 2023
dpb
on 24 Apr 2023
Show us a SMALL working example that illustrates the issue; while I haven't done it, it's hard to imagine the doc example doesn't work...which specific release are you using?
I dunno if can do this interactively here or not...
function hitcallback_ex1(src,evnt)
if strcmp(evnt.Peer.Visible,'on')
evnt.Peer.Visible = 'off';
else
evnt.Peer.Visible = 'on';
end
end
plot(rand(4));
l = legend('Line 1','Line 2','Line 3','Line 4');
l.ItemHitFcn = @hitcallback_ex1;
No, can't do that here, apparently; there's a whole lot about using this interface i've yet to learn/understand what can/cannot do...
Anyways, putting the above function into an m-file and executing the example code works as advertised here on R2020b...I presume it'll work on more recent releases as well...can toggle each and every line in the plot from the legend label associated...
alessandro marino
on 24 Apr 2023
Davindra Usov
on 25 Apr 2023
have you tried switch cases with a tiled layout. Search switch on matlab help
@Davindra Usov -- what's the issue you're raising? I don't follow; I just created a tiled layout and put a legend on each of two axes/tiles and assigned the above callback function to each. Both work as advertised with no need to do anything else...
% from example for tiledlayout...
x = linspace(0,30);
y1 = sin(x/2);
y2 = sin(x/3);
y3 = sin(x/4);
% Plot into first tile twice... (doc does three, but two's plenty to illustrate)
tiledlayout('flow')
nexttile
plot(x,y1)
hLg(1)=legend('Y1'); % add a legend; save the handle...
nexttile
plot(x,y2)
hLg(2)=legend('Y2'); % add a legend; save the handle...
hLg(1).ItemHitFcn = @hitcallback_ex1;
hLg(2).ItemHitFcn = @hitcallback_ex1;
After this, clicking on the legend entry in each toggles visibility of each as expected...
set(hLg,{'ItemHitFcn'},{@hitcallback_ex1})
is a more elegant syntax to set all handles to the one callback function.
Accepted Answer
More Answers (0)
Categories
Find more on Legend in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!