As both a programming language and interactive environment for data analysis, MATLAB provides extensive tools for visualizing and making sense of numeric data. A core capability is generating plots and charts from arrays of numbers, whether imported from files or generated via calculations, simulations, etc. This comprehensive guide will cover best practices and expert techniques for effectively plotting arrays in MATLAB.
Array Plotting Fundamentals
Before diving into specifics, let‘s quickly review some core principles to bear in mind:
Know Your Data First
Understand the structure, data types, value ranges, etc. of your arrays before plotting. This will guide which visualization makes the most sense. Use functions like size, length, and class to inspect arrays. Clean or preprocess where needed.
Match Plot Types to Data Characteristics
- Line plots: Continuous data over time/order
- Scatter: Individual datapoints
- Bar: Summary statistics or counts
- Pie: Part-to-whole comparisons
- Heatmaps: Matrix/grid-based intensity data
And many other domain-specific types like contour, surface, vector field plots, etc.
Know Your Audience and Goals
Tailor stylistic choices based on who will view plots and what insights you aim to achieve from visualization. Fancy 3D charts may look cool but simpler 2D may better highlight relationships.
Creating Arrays for Plotting
While the focus is on plotting, first you need arrays to plot from! Here are some common approaches:
1. Importing Data
Functions like readtable, csvread, load, and others ingest external data files into arrays in MATLAB‘s workspace. This data often comes from sensors, simulation outputs, spreadsheets, etc. Example:
temperatureData = readtable(‘temperatureLog.csv‘);
temperatures = temperatureData{:,‘Temperature‘};
2. Generating Data
Use MATLAB‘s matrix functions, random number generators, and other tools to programmatically generate arrays for plotting. Useful for testing and prototyping:
monthValues = 1:12;
rainfall = randi([5 12],1,12);
Here months 1-12 are in one array, random rainfall data in another.
3. Calculating Data
MATLAB excels at engineering and scientific calculations that produce array output ready for plotting:
[Y,F] = fft(inputSignal)
In this case taking the FFT of a signal to plot frequency spectrum. Vectorizing code to work on array inputs rather than looping leads to fast, efficient data processing.
Basic Array Plotting with plot()
The workhorse function for plots is the aptly named plot. Pass in x/y coordinate arrays:
x = 0:0.1:2*pi
y = sin(x)
plot(x, y)
And MATLAB plots the data, handling axis limits/scaling, line styles, etc automatically. Most often used for line charts but understands matrices for heatmap-style plots too.
While plot chooses defaults to get a quick visualization, understanding control options is key to polished publication plots.
Common plot() Customizations
‘LineSpec‘– change basic style with color, line styles, markers‘PropertyName‘, PropertyValue– fine tune thickness, sizexlabel/ylabel– axis labelstitle/legend– plot descriptionaxis– limits, log scale, etc.grid, box, and ticks – add reference lines
For example:
plot(x, sineData, ‘LineWidth‘, 2, ...
‘Marker‘, ‘o‘, ‘MarkerSize‘, 10, ...
‘Color‘, ‘#D95319‘);
ylabel(‘Sine Wave Amplitude‘)
xlabel(‘Angle (radians)‘)
legend(‘Sine Wave 1‘)
axis([0 7 -1.5 1.5])
Review the documenation for additional options.
"Figure" Concept for Multi-Plot View
MATLAB uses the concept of Figures as distinct visualization windows. Calling plot the first time creates fig 1. Further plots go there by default. Or use figure to open additional figs.
Want simultaneous plots? Call subplot to divide a figure into tiles for multiple views.
Expanding Past Basic Lines
While plot takes you a long way, MATLAB offers additional graphics functions to handle other data types.
Grouped Data: Bar Plots and Pie Charts
For categorical data or summary statistics where relative differences are key, opt for bar charts or pie visuals.
departments = {‘Sales‘,‘Marketing‘,‘Engineering‘};
headcount = [52, 33, 98];
bar(departments,headcount)
Use similar syntax for pie. Add titles and legends to highlight key group/category names.
Scatter Plots
When wanting to visually inspect the relationship between values in two arrays, scatter plots place a marker dot for each pair of (x,y) values:
x = linspace(0,10);
y = x.^2 + rand(1,11); % quadratic plus noise
scatter(x,y)
Can reveal trends like linear, exponential, clustering, outliers, etc. Use color and size codings via additional options.
Mesh and Surface Plots
For visualization based on gridded data (matrices), create mesh and surface plots. Color encodes a third dimension – typically height or an additional measurement value.
[X,Y] = meshgrid(-3:0.1:3);
Z = sinc(sqrt(X.^2 + Y.^2));
surf(Z)
Here building a matrix dataset and visualizing the sinc function surface. Useful for data sampled on a regular grid.
Large Datasets and Performance
Interactive plotting of small data is fast and easy in MATLAB. But for arrays with millions or more points, plotting can slow to a crawl. Some tips for high-performance vis:
- Sample/decimate datasets – only plot a relevant subset of large time series, Monte Carlo sims, etc.
- Use scatter for individual points rather than connecting lines
- Increase marker size rather than density for scatter
- Pre-calculate totals vs runtime sums in bar charts
- Use lower-level graphics functions like
imagesc,pcolor, and family
Also move computation not needed specifically for plotting out of loop iterations. And take advantage of MATLAB‘s vectorization instead of explicit loops.
If plotting speed still drags, may be time to switch from MATLAB‘s native graphics to Grammakov!
Preprocessing and Clearing Data
In practice, importing or calculating data often requires cleanup before plotting. Here is an example workflow:
rawData = load(‘experiment152.txt‘);
% Remove outliers
cleaned = rmoutliers(rawData)
% Filter to smoothed signal
filtered = smoothdata(cleaned,‘rloess‘,30);
% Plot the cleaned result
plot(filtered)
Common tasks include:
- Interpolating to fill in gaps
- Filtering noise
- Normalizing to a standard range
- Managing missing values
- Transforming non-linear scales
Use MATLAB‘s Statistics and Machine Learning toolbox, signal processing, and data wrangling functions to ensure you plot clean data revealing true relationships.
Annotations and Publication Quality Plots
For academic papers, presentations, or even exploring data during analysis, you often want to highlight aspects directly on the plot or add contextual text. This is where MATLAB‘s extensive annotation capabilities come into play.
Here are some top options for detailed, explainable figures:
title/xlabel/ylabel– Bold titles and axis labelstext– Custom text at any coordinatesgtext– Interactive click-to-place text boxesannotation– Draw lines/arrows/shapes/text- LaTeX markup for typesetting math equations
Bringing these together:
t = 0:0.01:1;
osc = sin(2*pi*t);
plot(t, oscillation)
title(‘Sine Wave Oscillating at $\omega = 2\pi$‘,‘Interpreter‘,‘latex‘)
xlabel(‘Time (s)‘)
ylabel(‘Amplitude‘)
x = [0.3 0.6];
y = [-1 1];
annotation(‘doublearrow‘,x,y)
txt = {‘Peak amplitude at 0.5 s‘,...
‘2 complete oscillation cycles over 1 s period‘};
text(0.1,0.75,txt)
This adds LaTeX math typesetting, an arrow annotation to highlight the axis crossing, and text callouts for features of note – extremely useful for reports and papers!
Exporting Plots
While you design plots interactively within MATLAB, often you need to save them stand-alone files for documents or sharing research visuals. Export using:
saveas(figureHandle,filename)– numerous image formats like PNGprint– vector formats including EPS, PDF- Markup languages like MATLAB2TikZ for LaTeX inclusion
Set resolution and scaling options to optimize exports for print vs electronic use.
Comparison to Python Visualization Landscape
As the open-source system for numerical computing, Python is MATLAB‘s biggest competitor. And with matplotlib plus libraries like seaborn, plotnine, bokeh, pygal and more, many argue Python excels for data visualization and charting.
So how does MATLAB graphics stack up to Python‘s ecosystem?
Python Pros
- More options and special-purpose libraries
- Easier custom styling with CSS and themes
- Interactivity widgets in notebooks
- Grammakov integration as high-performance backend
MATLAB Pros
- More polished default styles
- Easier MATLAB language integration
- Leverages computational toolchain for data analysis pipeline
- Standard input/output for reproducible automation
So while Python provides more flexibility, MATLAB excels at clean integration into the interactive workflow – especially when pairing analysis code seamlessly with visualization.
Tips and Tricks from Power Users
Let‘s wrap up with collected recommendations from seasoned MATLAB developers:
- Learn keyboard shortcuts for plotting/navigation – much faster
- Keep a set of utility scripts for common plot formats you reuse
- Use subplots wisely to enable multi-panel figures
- Style and size consistently when Planning multi-plot articles
- Add plot tags to enable programatic styling changes
- Take advantage of colororder for easier multi-line plots
- Use MATLAB‘s IDE tools for visual GUIs and apps too!
And above all, know Thy Data and Thy Audience! This will guide what visualizations work best.
Conclusion
In summary, MATLAB offers extensive functionality for plotting numeric arrays across a wide variety of chart and graphic styles. Coupled with tools for data import, cleaning, analysis, and annotation, it provides an integrated pipeline turning raw datapoints into publication-quality graphics and key insights. This guide shared best practices starting from fundamentals through specialized techniques employed by expert users. The key is matching desired understanding to graphical elements using MATLAB‘s flexible options.
Hopefully you find the 3000+ pointers and code samples here helpful for jumping to the next level with plotting arrays in your work! Please comment below with any additional visualization questions.


