MATLAB - Draw Rectangle
MATLAB - Drawing Rectangles in Plots
Section titled “MATLAB - Drawing Rectangles in Plots”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.
Modern Syntax and Usage
Section titled “Modern Syntax and Usage”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 handler = rectangle('Position', [x, y, w, h])
% Specify properties using name-value pairsr = rectangle('Position', pos, 'FaceColor', 'r', 'EdgeColor', 'b')
% Add curvature for rounded cornersr = 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")Core Concepts
Section titled “Core Concepts”'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 therectanglefunction 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 from0(no curve) to1(maximum curve). A value of[1, 1]creates an ellipse or a circle.- Target Axes (
ax): By default,rectangledraws on the current axes (retrieved withgca). To draw on a specific subplot or figure, you must pass the axes handle as the first argument.
Key Rectangle Properties
Section titled “Key Rectangle Properties”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').
Color and Styling Properties
Section titled “Color and Styling Properties”| Property | Description | Example Values |
|---|---|---|
FaceColor | Sets the interior fill color of the rectangle. | 'red', 'g', '#FFC0CB', [0.1 0.5 0.9] (RGB triplet), 'none' |
EdgeColor | Sets the color of the rectangle’s border. | 'blue', 'k', '#000000', [0 0 0] (RGB triplet), 'none' |
FaceAlpha | Controls the transparency of the fill color. 0 is fully transparent, 1 is fully opaque. | A scalar value from 0 to 1. Default is 1. |
LineWidth | Specifies the thickness of the border line in points. | A positive scalar value. Default is 0.5. |
LineStyle | Defines the style of the border line. | '-' (solid), '--' (dashed), ':' (dotted), '-.' (dash-dot), 'none' |
Behavioral Properties
Section titled “Behavioral Properties”| Property | Description | Values |
|---|---|---|
Visible | Controls whether the rectangle is rendered or hidden. | 'on' (default) or 'off' |
HandleVisibility | Controls if the object’s handle is visible in its parent’s list of children. Important for managing complex plots. | 'on' (default), 'callback', 'off' |
Practical Examples
Section titled “Practical Examples”Example 1: Basic Rectangle with Styling
Section titled “Example 1: Basic Rectangle with Styling”This example creates a basic plot and adds a styled, semi-transparent rectangle.
% Create a new figure and axesfigure;axis([0 10 0 10]); % Set plot limitshold on; % Allow multiple objects on the same axesgrid on;
% Define rectangle propertiespos = [2 2 5 3]; % [x, y, width, height]
% Draw the rectangle and store its handler = rectangle('Position', pos, ... 'FaceColor', [0.5 0.7 1.0], ... % A light blue color 'EdgeColor', 'b', ... 'LineWidth', 2, ... 'LineStyle', '--');
% Add a labeltext(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 secondsr.FaceAlpha = 0.5; % Make it semi-transparenttitle('Updated with Transparency');Expected Output: A plot window appears with a dashed-border rectangle. After two seconds, the rectangle becomes semi-transparent.
Example 2: Annotating Data
Section titled “Example 2: Annotating Data”A common use case is to highlight a specific region in a data plot.
% Generate some sample datax = linspace(0, 2*pi, 100);y = sin(x) + 0.1*randn(1, 100);
% Create the plotfigure;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/2rectangle('Position', [pi/2, 0, pi, 1.2], ... 'FaceColor', [1 0.9 0.9], ... % Light red 'EdgeColor', 'none', ... 'FaceAlpha', 0.5);
% Add a text annotationtext(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.
Best Practices & Common Pitfalls
Section titled “Best Practices & Common Pitfalls”- Always Use
hold on: Before drawing a rectangle on an existing plot, usehold onto prevent the plot from being cleared. - Manage Axes Limits: The
rectanglefunction does not automatically adjust the plot’s axes limits. You may need to set them manually usingaxis()orxlim()/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 withCurvature=[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.