Does Matlab execute a callback when a plot is zoomed/resized/redrawn? - matlab

In Matlab, I would like to update the data plotted in a set of axes when the user zooms into the plot window. For example, suppose I want to plot a particular function that is defined analytically. I would like to update the plot window with additional data when the user zooms into the traces, so that they can examine the function with arbitrary resolution.
Does Matlab provide hooks to update the data when the view changes? (Or simply when it is redrawn?)

While I have yet to find one generic "redraw" callback to solve this question, I have managed to cobble together a group of four callbacks* that seem to achieve this goal in (almost?) all situations. For a given axes object ax = gca(),
1. Setup the zoom callback function as directed by #Jonas:
set(zoom(ax),'ActionPostCallback',#(x,y) myCallbackFcn(ax));
2. Setup a pan callback function:
set(pan(ax),'ActionPostCallback',#(x,y) myCallbackFcn(ax));
3. Setup a figure resize callback function:
set(getParentFigure(ax),'ResizeFcn',#(x,y) myCallbackFcn(ax));
4. Edit: this one no longer works in R2014b, but is only needed if you add, e.g., a colorbar to the figure (which changes the axis position without changing the figure size or axis zoom/pan). I've not looked for a replacement. Finally, setup an undocumented property listener for the axes position property itself. There is one important trick here: We must hold onto the handle to the handle.listener object as once it's deleted (or leaves scope), it removes the callback. The UserData property of the axes object itself is a nice place to stash it in many cases.
hax = handle(ax);
hprop = findprop(hax,'Position');
h = handle.listener(hax,hprop,'PropertyPostSet',#(x,y) myCallbackFcn(ax));
set(ax,'UserData',h);
In all these cases I've chosen to discard the default callback event arguments and instead capture the axis in question within an anonymous function. I've found this to be much more useful than trying to cope with all the different forms of arguments that propagate through these disparate callback scenarios.
*Also, with so many different callback sources flying around, I find it invaluable to have a recursion check at the beginning of myCallbackFcn to ensure that I don't end up in an infinite loop.

Yes, it does. The ZOOM mode object has the following callbacks:
ButtonDownFilter
ActionPreCallback
ActionPostCallback
The latter two are executed either just before or just after the zoom function. You could set your update function in ActionPostCallback, where you'd update the plot according to the new axes limits (the handle to the axes is passed as the second input argument to the callback).

Related

Why is MATLAB's legend function so slow, and how to optimize?

Problem
In a GUI I've written I've realized that the largest bottleneck in my code performance is creating/updating the legend.
Currently I delete and recreate the legend at each update of the GUI as the user needs to be able to adjust what is in the legend. I'm currently toggling what is in the legend by adjusting the setting of LINEHANDLE.Annotation.LegendInformation.IconDisplayStyle and updating the legend using legend('off');legend('show');
Testing
The following code snippet shows that the call of legend mostly is limited by the call to legend>make_legend and is fairly independent of the legend content.
close all
n=50; % number of plot lines
S=rand(n); % data
legs=cellstr(char(26*rand(n,10)+97)); % legend entries
profile on %start profiler
plot(S)
legend(legs{:})
profile viewer % view call stats
Question
Is there a better way of updating legend content without deleting it and therefore forcing it to re-call make_legend at recreation?
Furthermore I wonder if it is known why legend in general is so slow and has such odd behavior.
Purpose
I'm adding some information here to avoid the XY Problem.
A minimal example of what I'm trying to do is:
I'm building a GUI which plots four lines, let's call them data1, data2, linear model 1, and linear model 2. The data lines are independent in both color and content, while the linear models both have the same appearance and are connected to respective data line.
I want there to be a legend which only has three entries: data1, data2, and linear model. So far, no problem.
I also want there to be three toggle-buttons which toggle the visibility of the four lines on the axes and legend. The buttons are:
data1, which toggles the visibility of both the data1, and linear model 1 data lines.
data2, which toggles the visibility of both the data2, and linear model 2 data lines.
linear model, which toggles the visibility of the linear model 1, and linear model 2 data lines.
Attempted Solutions
My first approach was to first only pass three handles to legend and then have the button callbacks adjust the visibility property of the line objects according to above.
This creates the issue that when disabling the first data line and respective linear model the legend entry for linear model also blanks out as it is connected to that specific line object, even though the other is still visible.
My current working approach instead manually sets the DisplayNameproperty of all lines and then the button callbacks adjust each lines Annotation.LegendInformation.IconDisplayStyle property. According to the documentation the user then needs to call legend to force an update.
But this is not implemented, looking at the code of legend.m it is clear that this option only returns the current legend object without any other manipulation. Therefore I'm forced to call legend('off');legend('show'); which triggers a (slow) creation of a new legend object.
This currently works but using profile I can see that the legend creation is half my computation time and has a fairly large effect on user experience when using the GUI on a slower laptop. I've already ensured that my code runs legend('off');legend('show'); only if it really has to.
The question is if any user here is able to call the unreadable, yet accessible class methods of matlab.graphics.illustration.Legend to trigger an update of an existing object without forcing it to delete and recreate. Thereby doing what the MATHWORKS documentation claims to be implemented (although it is not) in legend.
Alternatively I'm open to finding a different way of changing which line objects the current legend is tracking efficiently.
You can try to change the properties of the legend object directly. Look at http://www.mathworks.com/help/matlab/ref/legend-properties.html for a list of properties. The legend object can be accessed by:
% Assign the output of legend to a variable. Do this only once at creation.
l = legend(<some arguments>);
% Example: change the location of the legend to 'north'
l.Location = 'north';
I think this is what you asked for, but I'm not sure about any efficiency gains.

Multiple property listeners wait for both to trigger callback

I am having a little trouble in Matlab regarding property listeners. I have added a listener to the XLim and YLim properties of an axis, triggered on PostSet:
h = addlistener(myaxes,{'XLim','YLim'},'PostSet',#myfunc);
Now I want my program to do something after both properties have changed, or if only one has changed, but in the latter case I must be sure that the other one was not changed.
When using the zoom tool on the axes, the properties always change both and always in the order x, then y. So in this case I would not have a problem, but sometimes I am setting the XLim or YLim properties programmatically and want the same function to trigger. Somehow I must be able to tell if only one of these two properties has triggered the listener or both.
In the current stage, my callback executes twice: once for XLim and once for YLim. I want it to execute exactly once, and exactly after I know there is no further change to the two properties. Do you have any idea how to do this?
I don't believe it can be possible to detect the "simultaneous" set directly, because the actual property assignments, not just the PostSet events, are executed separately, and no additional information is passed to the PostSet callback that lets you know another one is coming. Stopped on a breakpoint in the first callback, the axes fully update to their new XLim without any sign of the coming change to YLim.
There are quite a number of ways to put together a workaround depending on what you can assume about the way the code will be used and what your priorities are. All the ones I can think of use at least one of the following principles:
Use a timer at some stage to allow for a possible YLim assignment to trigger a second callback before completing the work of an XLim PostSet callback
Create a custom routine for assignment of XLim without YLim to differentiate in some way from assignments made by things like the zoom tool
Make use of the fact that the zoom tool sets the XLimMode property first, whether or not there is a change to its value. Setting XLim programmatically will not set XLimMode if its value is already manual.

Communication between two or more GUIs

I've a GUI(i.e. lets call it 'First')through which i can choose to open other GUIs(let's call them 'Second' and 'Third').I want to put a 'pushbutton' on the 'First'GUI that allows me to manipulate the figure on the different axes of the 'Second' and 'Third' GUIs. So, i choose with the 'First'GUI if use either 'Second' or 'Third' GUI; once i've chosen that i start to work just with the GUI that i chose (so the Third one or Second ones). Now i want to have a pushbutton not on each GUIs (Second or Third) but only on the First one in order to manipulate the figure on the axes 1 of the Second or Third (depends on which one i've previously chosen). Furthermore this pushbutton that i want is optional and i need to refresh my axes after used that.
I've done my best to explain the situation,please if you know any solution help me out!!Thanks
Your question is similar to other examples, such as this.
To understand how to solve your problem, you need to remember that MATLAB "decides" which axes to update based on the axes handle provided by the user. If the user doesn't provide a handle, a default gca (the current axes) is used. The axes that gca points to, is the first child of type 'axes' of the figure, that is, the first entry in findobj(hFigure,'Type','axes'). You can read about setting the current axes here.
Having established that, the solution you are looking for would involve storing the axes handles somewhere, and retrieving the correct one when you are about to update a plot. A common place to store it is the "application-defined data" (appdata), accessible by setappdata and getappdata, as mentioned in the first link above and also here.
The procedure you should undergo is:
Upon creating a figure, store the axes handle in appdata by calling setappdata(0,name,val) (e.g. setappdata(0,'axTag1',handles.axTag1)) from your GUI initialization function. The value 0 for the 1st argument stores it in MATLAB's root object (you can think of it as the main MATLAB window), so that even if any of the figures is closed, the information is maintained as long as MATLAB is still open.
Whenever you want to modify an axes, just obtain the appropriate handle using value = getappdata(0,name) and use it to update the corresponding axes.

Matlab Link data for a line graph on a scatter plot

I have a line which is plotted on another scatter plot. This line changes its shape from time to time. Is there any way by which I can specify in my program that the data for drawing this line is dynamic so that the plot updates by itself when the data changes?
Now what I am doing is draw the entire figure again after each data update. The program has very large number of iterations(>5000) and I need to visualize every change. That means figure should be drawn 5000 times. This is making my program very slow. Is there any other better way of doing this?
The refreshdata function might do what you want.
To automatically update a graph when a source variable changes, use the linkdata function. MathWorks has a is a great introduction page. However, there is a short example in the documentation:
x = [1:20];
y = rand(20,3);
area(x,y)
linkdata on
Then you can change a variable and the plot automatically redraws:
y(10,:) = 0;
Automatic update.
Note: Changing the source to a different variable entirely is a different thing. If YDataSource is reassigned, then refreshdata would be needed, as pointed out by Molly. Otherwise, this will keep your plot up-to-date when the variable changes.
One caveat is described on this page:
linkdata buffers updates to data and dispatches them to plots at roughly half-second intervals. This makes data linking not suitable for smoothly animating changes in data values unless they are updated in loops that are forced to execute two times per second or less.

Matlab: linkaxes squeezes my graph

I have drown several graphs thanks to "subplot" function on MatLab and it works well.
Nevertheless, I want all my graphs to have the same Y-scale so that I can compare them.
I used the "linkaxes" function and my all my graphs have the same scale but the problem is that some of my figures are "beheaded", lacking their upper part, or one of my figures is completely squeezed.
I don't get what happened. Could you please help me to solve the problem or tell me about another function that would be more appropriate in my case?
Here's part of my code:
for i=1:1:9
m=n(i);
fichier=sprintf('%d.txt',m);
M=load(fichier);
z=length(M(:,1));
x=M(1:z,1);
y=M(1:z,2);
a(i)=subplot(2,4,i)
contour3=plot(x,y)
linkaxes(a,'y')
end
linkaxes creates a permanent link between the scales of several axes, so that you can subsequently perform zoom operations (perhaps interactively) on one, and have the other automatically update.
If you need that functionality, then linkaxes is the right command (although you could possibly also look at linkprops).
However if all you need is to ensure that the y-axis limits of your axes are the same, it will probably be easier (and you will have more control) if you set them directly. You can retrieve the y-axis limits using ylim(axis_handle) and set them using ylim(axis_handle, [lower, upper]), or alternatively with get(axis_handle,'YLim') and set(axis_handle,'YLim',[lower,upper]). You might also look at the YLimMode property of the axis, which determines whether the axis limits are directly set or automatically resized.