Matlab 2025 axes zoom error when the x axis is scaled differently.

10 views (last 30 days)
Hi all,
When I run this code on matlab 2025a, both plots look the same. However, when I use the zoom tool (by just clicking somewhere in the middle of the plot), then the axis line of the right plot displays over everything else.
% make bad graph
a = randn(1,1000);
fs = 5e7;
figure
tiledlayout(1, 2);
nexttile;
plot( a);
nexttile;
t = (0:length(a) - 1)/fs;
plot( t, a);
Here is a screenshot:
Notice the line spilling onto the y-axis on only the right plot, but the left plot is properly cropped after zooming.

Accepted Answer

Jay
Jay on 7 Aug 2025
Okay, I reported the bug. But for others with the same problems, here is a workaround that adds listeners and crops the data appropriatly (the way that it should work when built in):
% make bad graph
a = randn(1,1000);
fs = 5e7;
figure
tiledlayout(1, 2);
nexttile;
plot( a);
ax = nexttile;
t = (0:length(a) - 1)/fs;
h = plot( t, a);
% Store original data
h.UserData.originalX = h.XData;
h.UserData.originalY = h.YData;
% Add listener for zoom and pan
addlistener(ax, 'XLim', 'PostSet', @(~,~) cropLineToAxes(ax, h));
addlistener(ax, 'View', 'PostSet', @(~,~) resetData(ax, h));
function cropLineToAxes(ax, h)
% Get original data
x = h.UserData.originalX;
y = h.UserData.originalY;
% Current axis limits
xlim = ax.XLim;
% Logical mask to keep only visible points
mask = x >= xlim(1) & x <= xlim(2);
% Apply the mask
h.XData = x(mask);
h.YData = y(mask);
end
function resetData(ax, h)
% Get original data
x = h.UserData.originalX;
y = h.UserData.originalY;
% Set it
h.XData = x;
h.YData = y;
% reset the figure
zoom(ax, 'out')
end

More Answers (0)

Categories

Find more on Graphics Object Programming in Help Center and File Exchange

Products


Release

R2025a

Community Treasure Hunt

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

Start Hunting!