Guide
Figures, sound & data
Everything that leaves the console: plots, figures for papers, animations, sound and data that comes in from files and the web.
Lines and markers
A style string combines a colour (r g b c m y k), a line (- -- : -.) and a marker (o . x + * s d ^ v). Name–value pairs such as 'LineWidth', 'Color' and 'DisplayName' fine-tune it. hold on keeps adding to the same axes.
x = linspace(0, 2*pi, 200);
plot(x, sin(x), 'b-', x, cos(x), 'r--', 'LineWidth', 1.6)
hold on
plot(x(1:20:end), sin(x(1:20:end)), 'ko')
hold off
legend('sin', 'cos', 'samples'), xlabel('x'), title('Line styles: colour, dash, marker')Try it ↗Charts
bar, barh, histogram, pie, boxplot, area, stairs, stem, errorbar, scatter and more. subplot(rows, cols, k) puts several in one figure and sgtitle titles them all.
subplot(2, 2, 1), bar([4 7 3 5]), xticklabels({'A', 'B', 'C', 'D'}), title('bar')
subplot(2, 2, 2), histogram(randn(1, 2000), 30), title('histogram')
subplot(2, 2, 3), pie([45 30 25], {'x', 'y', 'z'}), title('pie')
subplot(2, 2, 4), boxplot([randn(80, 1), 1 + 0.6*randn(80, 1)]), title('boxplot')Try it ↗Surfaces and fields
surf, mesh, contour, contourf, imagesc, quiver and plot3. Drag 3D plots to rotate them; view, colormap, shading and colorbar set them up from code.
[X, Y] = meshgrid(linspace(-3, 3, 50));
Z = peaks(X, Y);
subplot(1, 2, 1), surf(X, Y, Z), shading interp, colormap turbo, title('surf')
subplot(1, 2, 2), contourf(X, Y, Z, 12), colorbar, axis equal tight, title('contourf')Try it ↗Figures for papers, slides and the web
A style sets fonts, line widths, colours, grid and the export size in one line. The preview then shows the exact page you will export.
| style | for | size |
|---|---|---|
default | MathLab look: follows the site theme | — |
web | Same as default; tuned for screens | — |
paper | Journal-ready: white, serif text, colour-blind-safe lines, no grid | 6 × 4.2 in, 300 dpi |
ieee | IEEE single column (3.5 in), Times, 8–9 pt | 3.5 × 2.6 in, 600 dpi |
ieee-wide | IEEE two-column width (7.16 in) | 7.16 × 3.2 in, 600 dpi |
nature | Nature-style single column (89 mm), Helvetica, 7–8 pt | 3.5 × 2.6 in, 600 dpi |
thesis | Book/thesis page width, serif | 5.8 × 3.8 in, 300 dpi |
slides | Presentations: large text, thick lines, 16:9 | 13.33 × 7.5 in, 150 dpi |
poster | Posters: very large text and lines | 10 × 7 in, 300 dpi |
minimal | Tufte-like: no frame, no grid, quiet axes | — |
grayscale | Black and white print: black lines told apart by dashes | 6 × 4.2 in, 300 dpi |
dark | Dark background | — |
light | Light background | — |
MATLAB's own commands work on top: fontsize, fontname, colororder, theme, and set(gca, …) / set(gcf, 'Units', 'centimeters', 'Position', […]). exportgraphics, saveas and print offer the file as a download; the Export menu has the same with size presets. PDF and PNG carry the resolution you choose (PDF holds a high-resolution image); SVG is vector and opens in Inkscape and Illustrator.
style ieee
x = linspace(0, 5, 100);
plot(x, exp(-x).*cos(4*x), x, exp(-x), '--')
xlabel('t (s)'), ylabel('response')
legend('signal', 'envelope')
exportgraphics(gcf, 'response.pdf', 'Resolution', 600)Try it ↗Animation
Add animate(seconds) and use the time variable t. MathLab runs the script for every frame; the play bar pauses, scrubs and changes speed, and Export → Record animation saves a video.
animate(6) % a 6-second animation; t runs from 0 to 6
x = linspace(0, 4*pi, 300);
plot(x, sin(x - 2*t) .* exp(-x/10), 'LineWidth', 2)
ylim([-1 1]), title(sprintf('t = %.1f s', t))Try it ↗Sound
sound(y, fs) plays samples between −1 and 1 at fs samples per second; soundsc scales them first; an N×2 matrix is stereo. audiowrite('name.wav', y, fs) offers a WAV download, and [y, fs] = audioread('clip.wav') reads an imported one.
fs = 22050; tt = 0:1/fs:1.5;
f = 220 * 2.^(floor(tt*4)/12); % a rising scale, 4 notes per second
y = sin(2*pi*cumsum(f)/fs) .* exp(-mod(tt, 0.25)*8);
sound(0.5*y, fs)
plot(tt, y), xlabel('time (s)'), title('A rising scale')Try it ↗Images
Images are arrays: rows × columns for grey, rows × columns × 3 for colour, usually uint8 (0–255). imread reads imported PNG, JPEG, GIF and WebP files and image web addresses (large photos are scaled down to 1024 pixels); imshow, montage and imshowpair show them and imwrite saves them. Filters (imfilter, fspecial, imgaussfilt, medfilt2), edges (edge, imgradient), histograms and contrast (imhist, histeq, imadjust), geometry (imresize, imrotate, imcrop), morphology (strel, imopen, imfill) and measurement (bwlabel, regionprops) follow MATLAB's Image Processing Toolbox. testimage, phantom and checkerboard give pictures to practise on. See the images tutorial.
I = testimage('shapes'); % or imread('photo.jpg') after Import
G = rgb2gray(I);
subplot(1, 3, 1), imshow(I), title('image')
subplot(1, 3, 2), imshow(imgaussfilt(G, 2)), title('blurred')
subplot(1, 3, 3), imshow(edge(G, 'canny')), title('edges')Try it ↗Data from files and the web
Import (or drop files on the editor) adds CSV, JSON, text and WAV files; they stay in your browser and are listed in the Files tab. Read them with readtable, readmatrix, fileread, jsondecode or audioread. Web addresses written in the script are fetched before it runs: webread turns JSON into structs and CSV into tables. The website has to allow access from other pages (CORS) — open data services such as the World Bank API and files on GitHub do. writetable and writematrix save results as CSV downloads.
T = readtable('https://raw.githubusercontent.com/datasets/global-temp/main/data/annual.csv');
g = strcmp(T.Source, 'GISTEMP');
bar(T.Year(g), T.Mean(g))
xlabel('year'), ylabel('°C vs 1951–1980'), title('Global temperature anomaly (NASA GISTEMP)')Try it ↗