You are now following this Submission
- You will see updates in your followed content feed
- You may receive emails, depending on your communication preferences
Overview
By default, MATLAB legends are static. This utility provides a generic callback function that allows you to click on any legend item to toggle the visibility of the corresponding plot on and off.
Furthermore, it includes instructions on how to set this behavior as the global default for your MATLAB environment.
Key Features
- Zero-code interactivity: Once set up in startup.m, standard plot() and legend() commands become instantly clickable.
- Grouped Object Support: If your plot includes auxiliary graphics (like shaded confidence intervals, error bars, or scatter points), you can group them with the main line using the UserData property. Clicking the legend will hide/show the entire group seamlessly.
- UI Integration: Automatically detects and triggers sliders or other UI callbacks if present in the figure, ensuring interactive apps update correctly when lines are hidden.
Installation & Setup
- Download defaultLegendClick.m and place it somewhere permanently in your MATLAB Path (e.g., your default Documents/MATLAB folder).
- To make this behavior automatic, open or create your startup.m file and add the following line:set(groot, 'defaultLegendItemHitFcn', @defaultLegendClick);
Example 1: Basic Usage (Automatic)
Once installed in your startup file, standard plotting works instantly:
x = 0:0.1:10;
plot(x, sin(x), 'DisplayName', 'Sine');
hold on;
plot(x, cos(x), 'DisplayName', 'Cosine');
legend(); % Click the legend text to hide/show lines!
Example 2: Advanced Usage (Grouped Objects)
If you want to hide a line AND a shaded boundary at the same time, bundle them in the UserData property of the main line:
x = 1:10; y = rand(1, 10);
variance = 0.2 * ones(1, 10);
figure; hold on;
% 1. Plot the main line
h_line = plot(x, y, 'b-', 'LineWidth', 2, 'DisplayName', 'Data');
% 2. Plot the shaded region (turn off HandleVisibility so it isn't in the legend)
h_fill = fill([x, fliplr(x)], [y+variance, fliplr(y-variance)], 'b', 'FaceAlpha', 0.2, 'EdgeColor', 'none', 'HandleVisibility', 'off');
% 3. Bundle them together so the callback knows to toggle both!
set(h_line, 'UserData', [h_line, h_fill]); legend();
% Clicking "Data" will now hide BOTH the line and the fill!
Example 3: Comprehensive Standalone Test Suite
Below is a fully self-contained script that demonstrates the clickable legend functionality working seamlessly across nine different types of MATLAB plots (Line, Scatter, Bar, Errorbar, 3D, Polar, Histogram, Dual Y-Axis, and grouped objects). The callback function is included at the very bottom of the script, so you can copy, paste, and run it immediately to see it in action without needing to set up your path.
% =========================================================================
% TEST SUITE: Universal Clickable Legends
% =========================================================================
clear; clc; close all;
% 1. Set the global default behavior for this session
set(groot, 'defaultLegendItemHitFcn', @defaultLegendClick);
disp('Global default legend click behavior set!');
disp('Please click the legends in the generated figure to test various plot types.');
% 2. Setup Figure and Layout
fig = figure('Name', 'Legend Click Test Suite', 'Position', [100, 100, 1200, 800]);
t = tiledlayout(3, 3, 'TileSpacing', 'compact', 'Padding', 'compact');
title(t, 'Universal Clickable Legend Testing Suite', 'FontWeight', 'bold', 'FontSize', 16);
%% Test 1: Standard Line Plots
nexttile; hold on; grid on;
plot(1:10, rand(1,10), 'LineWidth', 2, 'DisplayName', 'Line A');
plot(1:10, rand(1,10), 'LineWidth', 2, 'DisplayName', 'Line B');
title('1. Standard Lines');
legend();
%% Test 2: Scatter Plots
nexttile; hold on; grid on;
scatter(rand(1,20), rand(1,20), 50, 'filled', 'DisplayName', 'Group 1');
scatter(rand(1,20), rand(1,20), 50, 'filled', 'DisplayName', 'Group 2');
title('2. Scatter Plots');
legend();
%% Test 3: Bar Charts
nexttile; grid on; hold on;
b = bar([rand(5,1), rand(5,1)]);
b(1).DisplayName = 'Metric 1';
b(2).DisplayName = 'Metric 2';
title('3. Bar Charts');
legend();
%% Test 4: Error Bars
nexttile; hold on; grid on;
x = 1:5;
errorbar(x, rand(1,5), 0.1*ones(1,5), 'LineWidth', 1.5, 'DisplayName', 'Exp 1');
errorbar(x, rand(1,5), 0.2*ones(1,5), 'LineWidth', 1.5, 'DisplayName', 'Exp 2');
title('4. Error Bars');
legend();
%% Test 5: 3D Plots (Surface & Line)
nexttile; hold on; grid on; view(3);
surf(peaks(15), 'FaceAlpha', 0.8, 'DisplayName', 'Surface Data');
plot3(1:15, 1:15, rand(1,15)*5, 'r', 'LineWidth', 3, 'DisplayName', '3D Trajectory');
title('5. 3D Plots');
legend();
%% Test 6: Polar Plots
ax_polar = polaraxes(t);
ax_polar.Layout.Tile = 6; hold(ax_polar, 'on');
polarplot(ax_polar, linspace(0, 2*pi, 50), rand(1,50), 'DisplayName', 'Antenna 1');
polarplot(ax_polar, linspace(0, 2*pi, 50), rand(1,50)+1, 'DisplayName', 'Antenna 2');
title(ax_polar, '6. Polar Plots');
legend(ax_polar);
%% Test 7: Histograms
nexttile; hold on; grid on;
histogram(randn(1,500), 'FaceAlpha', 0.5, 'DisplayName', 'Distribution A');
histogram(randn(1,500)+2, 'FaceAlpha', 0.5, 'DisplayName', 'Distribution B');
title('7. Histograms');
legend();
%% Test 8: Dual Y-Axis (yyaxis)
nexttile; grid on;
yyaxis left;
plot(1:10, (1:10).^2, '-o', 'DisplayName', 'Left Axis (x^2)');
yyaxis right;
plot(1:10, 100./(1:10), '-s', 'DisplayName', 'Right Axis (100/x)');
title('8. Dual Y-Axis');
legend();
%% Test 9: Grouped UserData (The Confidence Interval trick)
nexttile; hold on; grid on;
x_dummy = linspace(0, 10, 50);
y_dummy = sin(x_dummy);
% Line and fill
h_main = plot(x_dummy, y_dummy, 'b', 'LineWidth', 2, 'DisplayName', 'Sine + CI');
h_fill = fill([x_dummy, fliplr(x_dummy)], [y_dummy+0.3, fliplr(y_dummy-0.3)], 'b', ...
'FaceAlpha', 0.2, 'EdgeColor', 'none', 'HandleVisibility', 'off');
% Bundle them together in UserData
set(h_main, 'UserData', [h_main, h_fill]);
plot(x_dummy, cos(x_dummy), 'r', 'LineWidth', 2, 'DisplayName', 'Cosine');
title('9. UserData Grouping');
legend();
% =========================================================================
% CALLBACK FUNCTION (Local Function)
% =========================================================================
function defaultLegendClick(~, event)
peer_handle = event.Peer;
handles_to_toggle = get(peer_handle, 'UserData');
if isempty(handles_to_toggle) || ~all(isgraphics(handles_to_toggle))
handles_to_toggle = peer_handle;
end
if strcmp(get(peer_handle, 'Visible'), 'on')
set(handles_to_toggle, 'Visible', 'off');
else
set(handles_to_toggle, 'Visible', 'on');
end
% Optional: Trigger external updates (e.g. your interactive zoom slider)
f = ancestor(peer_handle, 'figure');
if ~isempty(f)
sl = findobj(f, 'Style', 'slider');
if ~isempty(sl)
cb = get(sl, 'Callback');
if ~isempty(cb)
cb(sl, []);
end
end
end
end
Cite As
Matthias T (2026). Make Legends Clickable To Hide Plots (https://www.mathworks.com/matlabcentral/fileexchange/183772-make-legends-clickable-to-hide-plots), MATLAB Central File Exchange. Retrieved .
General Information
- Version 1.0.0 (1.62 KB)
MATLAB Release Compatibility
- Compatible with any release
Platform Compatibility
- Windows
- macOS
- Linux
| Version | Published | Release Notes | Action |
|---|---|---|---|
| 1.0.0 |
