Search code examples
matlabplotpropertiesannotationsmatlab-figure

How can I plot objects outside of an axes using Line or annotation objects in MATLAB?


I want to create a line with circular markers at each data point outside the axes in a MATLAB figure, similar to what

line([x1 x2],[y1 y2],'Color','k','Marker','o')

would produce.

To place the line object outside the axes, I have simply tried using annotation:

annotation('line',phi1([x1 x2]),phi2([y1 y2]),'Color','k','Marker','o')

where phi1 and phi2 are appropriate coordinate transforms to fit the coordinates x and y inside the axes of the current figure.

I expected this to work since line objects have a marker property. However, with annotation, I am getting the following error message:

Error using matlab.graphics.shape.Line/set
There is no Marker property on the Line class.

Error in matlab.graphics.chart.internal.ctorHelper (line 8)
    set(obj, pvpairs{:});

Error in matlab.graphics.shape.Line

Error in annotation (line 128)
        h = matlab.graphics.shape.Line(aargs{:});

Similarly, when plotting a rectangle with the annotation function, one cannot set the Curvature property. It seems that annotation does not support these kinds of properties, even though it creates a line or rectangle object just like the line or rectangle functions would. I tried fiddling around with the annotation handles and children, but no success there.

Any ideas for a workaround?


Solution

  • The different types of annotation objects are a separate set of class types than the usual line or rectangle objects, supporting a reduced set of properties. For example, a typical line object is of class type matlab.graphics.primitive.Line, but an annotation line object is of class type matlab.graphics.shape.Line.

    Instead of using annotation objects, you can simply set the 'Clipping' property of the line and rectangle objects to 'off' to allow them to individually render outside of the axes limits. For example, this code:

    hAxes = subplot(1, 2, 1);
    axis(hAxes, [0 1 0 1]);    % Freeze axis limits
    hLine = line([0.5 2], [0.5 0.5], 'Color', 'k', ...
                                     'Marker', 'o', ...
                                     'Clipping', 'off');
    hRect = rectangle(hAxes, 'Position', [1.5 0.1 1 0.25], ...
                             'Curvature', [0.2 0.2], ...
                             'FaceColor', 'r', ...
                             'Clipping', 'off');
    

    Produces this plot:

    enter image description here

    Alternatively, you can turning clipping off for all objects of an axes by turning the 'Clipping' property of the axes to 'off'.