Search code examples
matlabuser-interfacematlab-figure

How to set uicontextmenu for contourf (MATLAB2014b)


Originally I asked why pcolor and contourf don't work with this method, and I assumed they were symptoms of the same problem. This is not true, hence the new question.

Why does this not work with contourf? (and how do i get it to work?)

axes; 
stuff = uicontextmenu('Parent',ancestor(axes,'figure')); 
stuffm = uimenu('Parent',stuff,'Label','Change something'); 
x = randn(10); 
h = contourf(x);
% pcolor works! contourf does not
%h = pcolor(x) 
set(h,'uicontextmenu',stuff);    

Solution

  • You're trying to assign the context menu to the wrong object.

    The first output of contourf, as noted in the docs, is the "contour matrix", you want the handle to the object:

    [M,c] = contourf(___) returns the contour matrix and the contour object c. Use c to set properties after displaying the contour plot.

    So just change your code as follows:

    [~,h] = contourf(x); % 2nd output is the object handle
    set(h,'uicontextmenu',stuff);
    

    Result is a working context menu:

    context menu

    Note you were also creating axes twice, I think the 2nd time is unintentional when creating the context menu, fix this like so:

    ax = axes; % assign new axes to variable for later use
    stuff = uicontextmenu('Parent',ancestor(ax,'figure')); % use ax, not new axes