Skip to content

MATLAB - Draw Rectangle

In MATLAB, the rectangle function is a versatile tool for adding rectangular shapes to your plots. This is essential for various visualization tasks, such as highlighting specific regions of interest in data, annotating graphs, or building basic graphical user interfaces. Understanding how to control a rectangle’s position, size, and appearance is a fundamental skill in MATLAB graphics.

The rectangle function creates a Rectangle object. You can control its properties during creation using name-value pairs or modify them later using the object handle. The modern syntax is highly readable and flexible.

% Recommended: Create a rectangle and store its handle
r = rectangle('Position', [x, y, w, h])
% Specify properties using name-value pairs
r = rectangle('Position', pos, 'FaceColor', 'r', 'EdgeColor', 'b')
% Add curvature for rounded corners
r = rectangle('Position', pos, 'Curvature', [h_curv, v_curv])
% Draw in a specific axes handle 'ax'
r = rectangle(ax, 'Position', pos)
% Using modern Name=Value syntax (R2021a and later)
r = rectangle(Position=pos, FaceColor="red")
  • 'Position', [x, y, w, h]: This is the most important property. It’s a four-element vector where [x, y] defines the coordinates of the bottom-left corner, and [w, h] defines the width and height, respectively.
  • Graphics Handle (r): Storing the output of the rectangle function into a variable (e.g., r) gives you a handle to the graphics object. This handle is crucial for modifying the rectangle’s properties after it has been drawn.
  • 'Curvature', [h_curv, v_curv]: This property allows you to create rounded rectangles. The curvature values range from 0 (no curve) to 1 (maximum curve). A value of [1, 1] creates an ellipse or a circle.
  • Target Axes (ax): By default, rectangle draws on the current axes (retrieved with gca). To draw on a specific subplot or figure, you must pass the axes handle as the first argument.

You can customize a rectangle’s appearance using its properties. Access and modify them using dot notation on the rectangle’s handle (e.g., r.FaceColor = 'blue').

PropertyDescriptionExample Values
FaceColorSets the interior fill color of the rectangle.'red', 'g', '#FFC0CB', [0.1 0.5 0.9] (RGB triplet), 'none'
EdgeColorSets the color of the rectangle’s border.'blue', 'k', '#000000', [0 0 0] (RGB triplet), 'none'
FaceAlphaControls the transparency of the fill color. 0 is fully transparent, 1 is fully opaque.A scalar value from 0 to 1. Default is 1.
LineWidthSpecifies the thickness of the border line in points.A positive scalar value. Default is 0.5.
LineStyleDefines the style of the border line.'-' (solid), '--' (dashed), ':' (dotted), '-.' (dash-dot), 'none'
PropertyDescriptionValues
VisibleControls whether the rectangle is rendered or hidden.'on' (default) or 'off'
HandleVisibilityControls if the object’s handle is visible in its parent’s list of children. Important for managing complex plots.'on' (default), 'callback', 'off'

This example creates a basic plot and adds a styled, semi-transparent rectangle.

% Create a new figure and axes
figure;
axis([0 10 0 10]); % Set plot limits
hold on; % Allow multiple objects on the same axes
grid on;
% Define rectangle properties
pos = [2 2 5 3]; % [x, y, width, height]
% Draw the rectangle and store its handle
r = rectangle('Position', pos, ...
'FaceColor', [0.5 0.7 1.0], ... % A light blue color
'EdgeColor', 'b', ...
'LineWidth', 2, ...
'LineStyle', '--');
% Add a label
text(pos(1), pos(2)-0.5, 'Styled Rectangle');
hold off;
title('Basic Rectangle with Styling');
% You can modify it later using the handle 'r'
pause(2); % Wait for 2 seconds
r.FaceAlpha = 0.5; % Make it semi-transparent
title('Updated with Transparency');

Expected Output: A plot window appears with a dashed-border rectangle. After two seconds, the rectangle becomes semi-transparent.

A common use case is to highlight a specific region in a data plot.

% Generate some sample data
x = linspace(0, 2*pi, 100);
y = sin(x) + 0.1*randn(1, 100);
% Create the plot
figure;
plot(x, y);
hold on;
title('Highlighting a Region of Interest');
xlabel('Time (s)');
ylabel('Amplitude');
% Highlight the area where the signal is positive between pi/2 and 3*pi/2
rectangle('Position', [pi/2, 0, pi, 1.2], ...
'FaceColor', [1 0.9 0.9], ... % Light red
'EdgeColor', 'none', ...
'FaceAlpha', 0.5);
% Add a text annotation
text(pi, 0.5, 'Area of Interest', 'HorizontalAlignment', 'center');
hold off;

Expected Output: A sine wave plot is displayed with a semi-transparent red rectangle highlighting the peak region of the wave.

  • Always Use hold on: Before drawing a rectangle on an existing plot, use hold on to prevent the plot from being cleared.
  • Manage Axes Limits: The rectangle function does not automatically adjust the plot’s axes limits. You may need to set them manually using axis() or xlim()/ylim() to ensure your rectangle is visible.
  • Perfect Squares and Circles: To ensure a rectangle with equal width and height appears as a square, use axis equal. Similarly, this will make a rectangle with Curvature=[1,1] appear as a perfect circle.
  • Performance: In loops where many rectangles are drawn, creating them all at once using vectorized inputs can be significantly faster than creating them one by one in a loop.