MATLAB GRAPHICS & Plotting
Computing for Engineers
Graphics and Plotting
Introduction
• MATLAB offers robust tools for graphical representation,
enabling users to visualize scientific and engineering data
effectively.
• It features extensive libraries for 2D/3D plotting, image
processing, and custom figure manipulation, allowing users
to move seamlessly from raw data analysis to publication-
ready presentations.
• To successfully master data visualization in MATLAB, consider
these key concepts:
• Basic 2D Plotting
Graphics and Plotting
Basic 2D Plotting
• The foundation of MATLAB graphics is the plot() function, which
creates basic 2D line plots.
• You can specify line colors, markers, and line styles right in the syntax.
• Example: plot(x, y, '--ro') plots data with a red dashed line and circle
markers.
• Helper Tools: Use hold on to overlay multiple plots on the same axes
without replacing the existing data.
Graphics and Plotting
Graphics
• Creating graphs using basic plotting functions
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)
Graphics and Plotting
Customizing Figures
• To make visualizations readable and presentation-ready,
MATLAB has simple, built-in commands to label your
graphics:
• Titles and Labels: title('My Data'), xlabel('Time (s)'),
ylabel('Amplitude’)
• Legends and Grids: legend('Data 1', 'Data 2'), grid on
• Axes Limits: xlim([0 10]) and ylim([-5 5]) to zoom in on
specific areas.
Graphics and Plotting
Customizing Figures
xlabel('x = 0:2\pi')
ylabel('Sine of x')
title('Sin Function','FontSize',12)
legend('Sin Function')
Graphics and Plotting
Graphics
• Plotting Lines and Markers
x1 = 0:pi/100:2*pi;
x2 = 0:pi/10:2*pi;
plot(x1,sin(x1),'r:',x2,sin(x2),'r+')
• Adding Plots to an Existing Graph
plot(x1,sin(x1))
hold on
plot(x1,cos(x1))
Graphics and Plotting
Using DisplayName
• If you are plotting data sequentially (e.g., using hold on), specify
the legend labels directly in your plot functions using the
'DisplayName' name-value pair.
plot(x, sin(x1), 'DisplayName', 'Sine');
hold on;
plot(x, cos(x2), 'DisplayName', 'Cosine');
hold off;
legend(); Graphics and Plotting
Customizing Location and Appearance
• You can assign the legend to a variable (e.g., lgd) to easily modify its
properties, such as moving its position or adding a title.
plot(x1, sin(x1), x2, cos(x2));
% Create the legend and adjust properties
lgd = legend('Sine', 'Cosine');
[Link] = 'southwest'; % Moves legend to the bottom left
corner
[Link] = 2; % Arranges labels in 2 columns
% Add a title
title(lgd, 'Functions'); Graphics and Plotting
Advanced 2D & 3D Visualizations
• For different types of datasets, you can utilize specialized
plot functions:
• Scatter,Line, Stem & Bar: scatter(x,y) for dispersed data
points, or bar(x,y) for categorical representations.
• Subplots: subplot(m, n, p) allows you to divide the figure
window into an \(m \times n\) grid and activate the \(p\)-
th plot.
Graphics and Plotting
Graphical Stem Plots
• If you want to plot discrete numerical data visually, you can use
MATLAB’s built-in stem function.
• This draws stems extending from the \(x\)-axis to terminate at the
specific data values.
t = 0:pi/100:2*pi;
y = sin(t);
stem(t,y)
Graphics and Plotting
Line Plot
t = 0:pi/100:2*pi;
y = sin(t);
plot(t,y)
Graphics and Plotting
Line Plot
xlabel(‘t’);
ylabel(‘sin(t)’);
title(‘The plot of t vs sin(t)’);
Graphics and Plotting
Line Plot
y2 = sin(t-0.25);
y3 = sin(t+0.25);
plot(t,y,t,y2,t,y3) % make 2D line plot of 3 curves
legend('sin(t)','sin(t-0.25)','sin(t+0.25',1)
Graphics and Plotting
Customizing Graphical Effects
Generally, MATLAB’s default graphical settings are adequate which make plotting fairly effortless.
For more customized effects, use the get and set commands to change the behavior of specific
rendering properties.
Z=peaks;
hp1 = plot(z) % returns the handle of this line plot
get(hp1) % to view line plot’s properties and their values
set(hp1, ‘lineWidth’) % show possible values for lineWidth
set(hp1, ‘lineWidth’, 2) % change line width of plot to 2
gcf % returns current figure handle
gca % returns current axes handle
get(gcf) % gets current figure’s property settings
set(gcf, ‘Name’, ‘My First Plot’) % Figure 1 => Figure 1: My First Plot
get(gca) % gets the current axes’ property settings
figure(1) % create/switch to Figure 1 or pop Figure 1 to the front
clf % clears current figure
close % close current figure; “close 3” closes Figure 3
close all % close all figures Graphics and Plotting
Save A Plot With print
x = magic(3); % generate data for bar graph
bar(x) % create bar chart
grid % add grid
• To add a legend, either use the legend command or via insert in the
Menu Bar on the figure. Many other actions are available in Tools.
• It is convenient to use the Menu Bar to change a figure’s properties
interactively. However, the set command is handy for non-interactive
changes, as in an m-file.
• Similarly, save a graph via the Menu Bar’s File / Save as or
>> print –djpeg 'mybar' % file [Link] saved in current dir
Graphics and Plotting
2D Bar Graph
x = magic(3); % generate data for bar graph
bar(x) % create bar chart
grid % add grid for clarity
Graphics and Plotting
Basic Scatter Plot
• To create a scatter plot in MATLAB, use the scatter(x,y) function,
passing two vectors of equal length for your \(x\) and \(y\)
coordinates.
• You can customize the plot with colors, marker sizes, and
transparency.
• A simple 2D plot maps points on a basic coordinate system.
% Create scatter plot
t = 0:pi/100:2*pi;
y = sin(t);
scatter(t, y); Graphics and Plotting
Customized Scatter Plot
• You can adjust the size, color, and fill of the markers
% Marker size (in points) and color mapped to values
% Create scatter plot
t = 0:pi/100:2*pi;
y = sin(t);
sz = 50;
c = t;
% Create filled scatter plot with a colormap
scatter(t, y, sz, c, 'filled', 'MarkerEdgeColor', 'k');
colorbar; % Adds a color scale
Graphics and Plotting
Common Optional Arguments
• You can tailor your scatter plots using optional arguments
right inside the scatter() function:
• 'filled': Fills the interior of the marker (requires a shape that
has a face, like 'o').
• MarkerEdgeColor: Sets the outline color of the marker.
• MarkerFaceColor: Sets the inside color of the marker
Graphics and Plotting
Grouped Scatter Plot
• If you have categories or groups within your data, you can
use gscatter to automatically separate and color the markers
by group
load carsmall; % Built-in MATLAB dataset
gscatter(Weight, MPG, Model_Year, 'bgr', 'xos');
Graphics and Plotting
Use MATLAB Command or Function ?
• Many MATLAB utilities are available in both command and function forms.
• For this example, both forms produce the same effect:
• print –djpeg 'mybar' % print as a command
• print('-djpeg', 'mybar') % print as a function
• For this example, the command form yields an unintentional outcome:
• myfile = 'mybar'; % myfile is defined as a string
• print –djpeg myfile % as a command, myfile is treated as text
• print('-djpeg', myfile) % as a function, myfile is treated as a variable
• Other frequently used utilities that are available in both forms are:
Graphics and Plotting
• save, load
Displaying Multiple plots in one Figure
t = 0:pi/10:2*pi;
[X,Y,Z] = cylinder(4*cos(t));
subplot(2,2,1); mesh(X)
subplot(2,2,2); mesh(Y)
subplot(2,2,3); mesh(Z)
subplot(2,2,4); mesh(X,Y,Z)
Graphics and Plotting
Creating 3D Graphics
To display a function of two variables, z = f (x,y),
• Generate X and Y matrices consisting of repeated rows and
columns, respectively, over the domain of the function.
• Use X and Y to evaluate and graph the function.
The meshgrid function transforms the domain specified by a
single vector or two vectors x and y into matrices X and Y for use in
evaluating functions of two variables.
The rows of X are copies of the vector x and the columns of Y are
copies of the vector y. Graphics and Plotting
• 3D Plots: Functions like plot3(x,y,z) for 3D lines or surf(X,Y,Z) for 3D surfaces and meshes.
x = -8:.5:8;
y = -8:.5:8;
z = -8:.5:8;
% . Create the 3D plot
figure;
plot3(x, y, 'LineWidth', 2, 'Color', 'b')
% Add labels and aesthetics
grid on;
xlabel('X-axis (sin)');
ylabel('Y-axis (cos)');
zlabel('Z-axis (t)');
title('3-D Helix Plot');
Graphics and Plotting
• Using the mesh function
[X,Y] = meshgrid(x,y);
R = sqrt(X.^2 + Y.^2) + eps;
Z = sin(R)./R;
mesh(X,Y,Z,'EdgeColor','black','LineStyle'
,'-','FaceColor','cyan')
• Using the surf function
surf(X,Y,Z)
colormap hsv
colorbar
Graphics and Plotting
3D Scatter Plot
• For plotting data with three variables (\(x\), \(y\), and \(z\)), use
scatter3(x,y,z)
x = rand(1, 100);
y = rand(1, 100);
z = rand(1, 100);
scatter3(x, y, z, 50, z, 'filled');
xlabel('X'); ylabel('Y'); zlabel('Z');
Graphics and Plotting
Surface Plot
surf(X,Y,Z) % surface plot of X,Y,Z
%Try these commands also:
shading flat
shading interp
shading faceted
grid off
axis off
colorbar
colormap(‘winter’)
colormap(‘jet’)
Graphics and Plotting
Contour Plots
Z = peaks;
contour(Z, 20) % contour plot of Z with 20 contours
contourf(Z, 20); % with color fill
colormap('hot') % map option
colorbar % make color bar
Graphics and Plotting
Plotting Images
• You can load any image using the imread command
[X,map] =
imread(‘image_name.jpg’)
• Once you have an image loaded you can plot it
using:
image(X)
colormap(map)
axis image Graphics and Plotting