MATLAB: GUIDE ButtonDownFcn callback does not work

buttondownfcncallbackguideMATLABnewplot

I have a simple script to reproduce the issue:
f = figure();
ax = axes(f);
plot(rand(5));
ax.ButtonDownFcn = @(hObject,eventdata)disp('Hi');
axes(ax);
plot(sin(1:0.01:25.99));
Seems the second plot() created a new axes, and callback wiring is lost. If only running the first four lines of code, callback is run fine with printing 'Hi' on the MATLAB Command Window, but if running the whole script, no callback will be run.

Best Answer

This happens because, when you call plot, under the hood plot calls 'newplot'. 'newplot' resets all the axes properties (including ButtonDownFcn).
You have several options to work around this:
1.Use a plotting command that does not call newplot. For example: the line command does not call newplot.
2.Call 'hold on' before you call plot. This will set the NextPlot property to 'add', which will prevent the axes properties from being reset.
3.You can manually set the NextPlot property on the axes to either 'add' or 'replacechildren' before you call plot.
4.You can attach the WindowButtonDownFcn to the figure instead of the ButtonDownFcn on the axes. WindowButtonDownFcn won't be reset by newplot by default.
5.You can manually restore the ButtonDownFcn after every call to plot.