Written and maintained by CASRAI Editorial Board
Last updated
MATLAB graphing functions generate 2-D and 3-D scientific visualizations from numeric arrays, experimental tables, and mathematical models. In academic and industrial research, researchers use coordinate plotting to evaluate simulation trajectories, display empirical distributions, and prepare vector graphics for peer-reviewed publication. This guide details core 2-D plotting syntax, axis styling, multi-panel layouts, and publication-ready export workflows using the modern graphics system.
What it is used for in research
In quantitative scientific research, visualizing data structures is essential for exploratory analysis, algorithmic debugging, and communicating empirical findings. The core matlab graphing functions provide an integrated environment where coordinate arrays map directly to high-precision figures. Researchers employ graphing functions in matlab across several primary domains:
- Experimental telemetry and time-series: Tracking sensor observations, biophysical waveforms, and instrument readouts over continuous or sampled time intervals.
- Simulation and numerical modeling: Visualizing differential equation solutions, dynamical systems trajectories, or solutions generated via a MATLAB equation solver.
- Statistical and empirical distributions: Inspecting dispersion, regression curves derived from an exponential regression curve fitting routine, and multivariate covariance structures such as a covariance matrix.
- Publication-quality figure generation: Producing vector-based PDFs or high-resolution raster images that satisfy stringent journal typesetting guidelines.
Install or access
MATLAB graphics capabilities require access to the core MATLAB mathematical computing environment provided by MathWorks. Academic researchers typically access MATLAB through one of two official avenues:
- Desktop Installation via MathWorks Installer:
- Log in to your MathWorks Account at
mathworks.com/downloadsusing your institutional or campus-wide license credentials. - Download the installer for your host operating system (Windows, macOS on Intel or Apple Silicon, or Linux).
- Launch the installer, authenticate with your licensed MathWorks Account, and select MATLAB along with relevant specialized toolboxes.
- Ensure hardware acceleration and graphics drivers (OpenGL) are current on your local machine for optimal 2-D and 3-D rendering performance.
- Log in to your MathWorks Account at
- Browser-Based Access via MATLAB Online:
- Navigate to
matlab.mathworks.comusing an HTML5-compliant web browser. - Sign in with your affiliated account credentials to launch an interactive cloud session without requiring local desktop installation or GPU configuration.
- Figures generated in MATLAB Online render directly within the web workspace and can be saved to MATLAB Drive or downloaded locally.
- Navigate to
Step-by-step task
The following step-by-step task demonstrates how to construct, format, and export a multi-series scientific plot using current MATLAB commands.
Step 1: Prepare coordinate arrays
Begin by defining your independent variable array and calculating corresponding dependent response vectors. Both vectors must share matching dimension sizes:
% Generate independent coordinate vector from 0 to 2*pi with 150 points
x = linspace(0, 2*pi, 150);
% Compute paired response curves
y_signal = sin(x);
y_damped = exp(-0.35 * x) .* sin(2 * x);
Step 2: Initialize figure container and execute plot
Call the figure function to create a clean figure container, followed by the primary plot command:
fig = figure('Color', 'white');
p1 = plot(x, y_signal, 'LineWidth', 1.8, 'Color', [0, 0.4470, 0.7410]);
Step 3: Overlay secondary data series
By default, calling plot again replaces the existing figure content. Use hold on to retain the existing series, plot additional series with distinct line styles or markers, and release the hold state with hold off:
hold on;
p2 = plot(x, y_damped, '--', 'LineWidth', 1.8, 'Color', [0.8500, 0.3250, 0.0980]);
hold off;
Step 4: Apply scientific annotations and styling
Format axes with descriptive labels, physical measurement units, mathematical notation using LaTeX or TeX markup, and a structured legend:
xlabel('Time, t (s)', 'FontSize', 11);
ylabel('Amplitude (V)', 'FontSize', 11);
title('Damped Harmonic Response vs. Reference Signal', 'FontSize', 12);
grid on;
set(gca, 'Box', 'on', 'TickDir', 'out', 'FontSize', 10);
legend([p1, p2], {'Reference Waveform', 'Damped Oscillation'}, ...
'Location', 'northeast', 'Box', 'off');
Step 5: Construct multi-panel layouts with tiledlayout
When compiling multiple panels for a manuscript, use modern tiledlayout and nexttile rather than legacy subplot to control padding and maintain consistent axis alignment:
fig_multi = figure('Color', 'white');
t = tiledlayout(1, 2, 'Padding', 'compact', 'TileSpacing', 'compact');
% Panel 1: Primary line response
ax1 = nexttile;
plot(ax1, x, y_signal, 'Color', [0, 0.4470, 0.7410], 'LineWidth', 1.5);
title(ax1, 'Reference Sine');
xlabel(ax1, 'Phase (rad)');
ylabel(ax1, 'Value');
grid(ax1, 'on');
% Panel 2: Damped response
ax2 = nexttile;
plot(ax2, x, y_damped, 'Color', [0.8500, 0.3250, 0.0980], 'LineWidth', 1.5);
title(ax2, 'Damped Waveform');
xlabel(ax2, 'Phase (rad)');
grid(ax2, 'on');
Step 6: Export publication-ready graphics
Modern MATLAB workflows use exportgraphics to produce tightly cropped figures without whitespace padding. For journal publication, export vector formats (PDF or EPS) or high-resolution raster images (TIFF or PNG at 300+ DPI):
% Export as publication-ready vector PDF
exportgraphics(fig_multi, 'Figure1_ResponseCurves.pdf', 'ContentType', 'vector');
% Export as 300 DPI high-resolution raster image
exportgraphics(fig_multi, 'Figure1_ResponseCurves.png', 'Resolution', 300);
Output and how to read it
When MATLAB executes a graphing script, it creates two primary graphics handle objects:
- The Figure Window (
Figureobject, accessed viagcf): The overall window container hosting axes, menus, and layout managers. Setting figure background color to white ('Color', 'white') ensures exported figures do not carry an unintended gray UI background. - The Axes Object (
Axesobject, accessed viagca): The geometric coordinate box that bounds plotting data. Reading an axis correctly involves inspecting the major and minor tick intervals, scientific notation scaling factors displayed at axis extremities, and data limit properties (XLim,YLim). - The Legend Box: Identifies series markers, dash patterns, and line colors. Positioning legends using semantic locations (such as
'northeast'or'best') prevents occluding observational data points.
Troubleshooting
Researchers commonly encounter specific execution and rendering challenges when managing MATLAB graphing workflows:
- Error: “Vectors must be the same length”:
This error occurs when the array passed to the horizontal coordinate argument does not match the number of elements in the vertical coordinate argument (for instance, passing a 150-element array for
xand a 149-element array fory). Use thewhoscommand orlength(x)andlength(y)in the command window to verify array dimensions. When computing numerical derivatives with functions likediff(x), the output is inherently one element shorter than the original input (N – 1), requiring trimming of the coordinate vector (e.g.,plot(x(1:end-1), diff(y))). - Overwritten plots and missing traces:
If sequential calls to
ploterase prior curves, verify thathold onis declared before calling subsequent plotting routines. Always close withhold offwhen figure assembly is complete to prevent subsequent script blocks from inadvertently drawing onto the active axes. - Headless execution on computing clusters (HPC):
When running batch simulation scripts on remote Linux servers or High-Performance Computing clusters without an active X11 display, calling figure creation commands can fail with display server errors. To prevent crashes, instantiate figures with visibility disabled:
fig = figure('Visible', 'off');. Theexportgraphicsfunction renders the figure offscreen and writes the graphic file directly to disk without requiring a graphical desktop environment. - Text clipping and border cropping:
Legacy functions like
saveasorprintfrequently clip long axis labels or title strings. Usingexportgraphicsautomatically calculates tight bounding boxes around all active annotations, eliminating manual bounding box recalculations.
Free alternatives
While MATLAB is an established standard in engineering and quantitative laboratories, research groups often evaluate open-source alternatives for reproducibility, cloud containerization, and cost efficiency. The following table compares leading open-source scientific graphing software against MATLAB:
| Software / Platform | Open-Source License | Primary Plotting Syntax | Key Strengths in Research | Typical Research Applications |
|---|---|---|---|---|
| GNU Octave | GNU General Public License (GPLv3) | High MATLAB compatibility (plot, xlabel, ylabel, hold on) |
Direct m-script syntax compatibility; native Qt/OpenGL and gnuplot toolkits | Running legacy MATLAB numerical simulations and plots without code rewrites |
| Python (Matplotlib and Seaborn) | Python Software Foundation (PSF) / BSD Compatible | Object-oriented (fig, ax = plt.subplots(); ax.plot()) |
Extensive scientific ecosystem; integrates with NumPy, SciPy, and machine learning pipelines | Data science workflows, automated reporting, and scalable cloud containerized figures |
| R (ggplot2) | GNU General Public License (GPLv2 / GPLv3) | Grammar of Graphics (ggplot(df, aes(x, y)) + geom_line()) |
Declarative aesthetic mapping; native support for tabular data structures and statistical models like data frames in R | Biostatistics, clinical trial visualization, bioinformatics, and academic publications |
| Julia (Plots.jl) | MIT License | Multi-backend interface (plot(x, y) via GR, PyPlot, or Plotly) |
High-performance numerical execution; fast compilation for heavy mathematical simulations | Computational physics, dynamical systems, and large-scale numerical modeling |
For enterprise-scale clinical and statistical data manipulation, institutions also compare these workflows against dedicated analytical platforms like SAS statistical software.
Frequently asked questions
Can you use MATLAB graphing online for free?
MathWorks provides browser-based access to MATLAB Online via matlab.mathworks.com. While individuals can explore basic tutorials, full graphing capabilities in MATLAB Online require an active MathWorks Account linked to a valid license (such as an institutional campus-wide license or individual license). Fully free open-source equivalents that run without licensing include GNU Octave and Python Matplotlib.
How do you adjust the plot legend position and appearance in MATLAB?
The legend command accepts name-value arguments to control positioning and frame styling. Use the 'Location' parameter with predefined orientations (e.g., 'northeast', 'southwest', 'northwest', or 'best'). Set 'Box', 'off' to remove the bounding frame, or set 'NumColumns', 2 to arrange legend entries into multiple columns.
How do you specify custom colors and line styles for MATLAB graphing?
MATLAB allows line customization either via compact format strings or explicit name-value pairs. Format strings combine color, marker, and line style specifiers (e.g., 'r--o' for red dashed line with circular markers). For precise publication palettes, pass an RGB triplet vector to the 'Color' argument (e.g., 'Color', [0.2, 0.6, 0.8]) and specify 'LineWidth' as a numeric scalar.
How does exportgraphics differ from the legacy saveas command?
Introduced in MATLAB R2020a, exportgraphics tightly crops exported files around titles, legends, and axes decorations, eliminating the unwanted peripheral whitespace often created by saveas. It also provides direct control over vector versus image rendering via 'ContentType' and explicit DPI resolution control via 'Resolution'.
Sources
- MathWorks. (2026). plot: 2-D line plot. MathWorks Documentation. https://www.mathworks.com/help/matlab/ref/plot.html (read 2026-11-07).
- MathWorks. (2026). exportgraphics: Save plot or graphics content to file. MathWorks Documentation. https://www.mathworks.com/help/matlab/ref/exportgraphics.html (read 2026-11-07).
- MathWorks. (2026). tiledlayout: Create tiled chart layout. MathWorks Documentation. https://www.mathworks.com/help/matlab/ref/tiledlayout.html (read 2026-11-07).
- MathWorks. (2026). MATLAB Online: Access MATLAB in your web browser. MathWorks Products. https://www.mathworks.com/products/matlab-online.html (read 2026-11-07).
- GNU Octave. (2026). Two-Dimensional Plots: High-Level Plotting. GNU Octave Documentation. https://docs.octave.org/latest/ (read 2026-11-07).







