askvity

How Does the Figure Command Work in MATLAB?

Published in MATLAB Graphics 3 mins read

In MATLAB, the figure command is used to create and manage figure windows, which are the containers for plots, charts, and other graphical elements.

What figure Does

At its core, the figure command creates a new figure window using default property values. When you call figure without any arguments, MATLAB opens a fresh window ready for you to plot into. This newly created figure automatically becomes the current figure, meaning subsequent plotting commands (like plot, scatter, bar) will draw into this window.

Customizing Figures with Name-Value Pairs

Beyond simply creating a default window, you can use figure( Name,Value ) to modify various properties of the figure as it's being created or to activate an existing figure. This allows for customization right from the start.

Syntax:

figure(Name, Value)

Where Name is the property name (as a string or character vector) and Value is the desired setting for that property.

Common Properties (Examples):

Property Name Description Example Usage
Name Title displayed in the figure window title bar figure('Name', 'My Plot Window')
NumberTitle Display figure number in title bar ('on'/'off') figure('NumberTitle', 'off')
Color Background color of the figure figure('Color', [0.9 0.9 0.9]) or figure('Color', 'w')
Position Size and location of the figure window [left, bottom, width, height] figure('Position', [100 100 800 600])

You can use multiple name-value pairs in a single figure command:

figure('Name', 'Experimental Results', 'Color', 'w', 'Position', [200 200 700 500]);

Using figure to Manage Multiple Windows

If you call figure multiple times, MATLAB creates multiple windows. The last one created or activated becomes the current figure.

You can also use figure(h) where h is the handle (a unique identifier) of an existing figure window. This command makes the figure with handle h the current figure, bringing it to the front of your screen.

Examples:

  1. Create a default figure:

    figure; % Opens a new, default figure window
    plot(rand(1,10)); % Plots into the new figure
  2. Create a figure with a specific title:

    figure('Name', 'Sales Data Analysis'); % Opens a figure with a custom title
    bar(1:5, [20 35 15 40 25]); % Plots into this titled figure
  3. Create two figures and switch between them:

    h1 = figure; % Create figure 1, get its handle
    plot(1:10, (1:10).^2); % Plot into figure 1
    
    h2 = figure; % Create figure 2, get its handle (figure 2 is now current)
    plot(1:10, sin(1:10)); % Plot into figure 2
    
    figure(h1); % Make figure 1 the current figure again
    title('Quadratic Growth'); % Add title to figure 1

In summary, the figure command is fundamental for managing graphical output in MATLAB, allowing you to create new windows and customize their appearance and behavior using various properties.

Related Articles