MATLAB - Plotting
MATLAB - Modern Plotting
Section titled “MATLAB - Modern Plotting”MATLAB is renowned for its powerful and flexible 2D and 3D plotting capabilities. Creating publication-quality visualizations is a core strength of the language. This guide covers the modern, object-oriented approach to creating and customizing plots.
The fundamental workflow for creating a plot involves these steps:
- 1. Prepare Data: Create the vectors or matrices that hold your data. The
linspacefunction is excellent for generating evenly spaced data for function plotting. - 2. Create a Figure: Use the
figurecommand to open a new window for your plot. - 3. Plot the Data: Use a plotting function like
plot,scatter, orbarto create the initial graph. It’s a best practice to get a handle to the plot object for later customization. - 4. Customize and Annotate: Add titles, axis labels, legends, and adjust colors, line styles, and other properties to make the plot clear and informative.
Creating a Basic 2D Plot
Section titled “Creating a Basic 2D Plot”Let’s plot the function y = sin(x) from 0 to 2π. Note the use of linspace to create a smooth curve.
% 1. Prepare Datax = linspace(0, 2*pi, 200); % Create 200 points from 0 to 2*piy = sin(x);
% 2. Create a Figurefigure;
% 3. Plot the Dataplot(x, y, 'LineWidth', 2); % Plot with a line width of 2
% 4. Customize and Annotatetitle('Plot of the Sine Function');xlabel('Angle (radians)');ylabel('sin(x)');grid on; % Add a gridaxis([0, 2*pi, -1.2, 1.2]); % Set axis limits [xmin, xmax, ymin, ymax]Plotting Multiple Functions on the Same Graph
Section titled “Plotting Multiple Functions on the Same Graph”The modern and most flexible way to plot multiple lines on the same axes is to use the hold on and hold off commands. This approach is more readable and extensible than older syntax.
x = linspace(0, 10, 150);y1 = sin(x);y2 = cos(x);
figure;plot(x, y1, 'b-', 'LineWidth', 2); % Plot sin(x) as a solid blue line
hold on; % Keep the current plot active for adding more lines
plot(x, y2, 'r--', 'LineWidth', 2); % Plot cos(x) as a dashed red line
title('Sine and Cosine Functions');xlabel('x');ylabel('Function Value');legend('sin(x)', 'cos(x)', 'Location', 'southwest'); % Add a legend
hold off; % Release the plot (new plots will replace it)grid on;Customizing Line Colors and Styles
Section titled “Customizing Line Colors and Styles”MATLAB provides extensive options for customizing the appearance of your plots. You can specify color, line style, and marker symbols as a single string argument or as separate name-value pairs.
| Specifier | Type | Values |
|---|---|---|
r, g, b, k, m, c, y, w | Color | Red, Green, Blue, Black, Magenta, Cyan, Yellow, White |
- | Line Style | Solid line (default) |
-- | Line Style | Dashed line |
: | Line Style | Dotted line |
-. | Line Style | Dash-dot line |
o, +, *, ., x, s, d | Marker | Circle, Plus, Asterisk, Point, Cross, Square, Diamond |
Example: plot(x, y, '--mo') creates a dashed magenta line with circle markers at each data point.
Creating Subplots
Section titled “Creating Subplots”The subplot function allows you to display multiple plots in a grid within a single figure window. The syntax is subplot(m, n, p), where m is the number of rows, n is the number of columns, and p is the index of the current plot (counted row-wise).
x = linspace(0, 5, 100);
figure;
% First subplot (top)subplot(2, 1, 1);y1 = exp(-1.5*x) .* sin(10*x);plot(x, y1);title('Subplot 1: Damped Sine Wave');ylabel('Amplitude');grid on;
% Second subplot (bottom)subplot(2, 1, 2);y2 = exp(-0.5*x) .* sin(10*x);plot(x, y2);title('Subplot 2: Less Damped Sine Wave');xlabel('Time (s)');ylabel('Amplitude');grid on;Exploring Other Plot Types
Section titled “Exploring Other Plot Types”MATLAB’s visualization library extends far beyond line plots. Here are a few other essential plot types:
scatter: Creates a scatter plot, ideal for visualizing the relationship between two variables.bar: Creates a bar chart, useful for comparing values across different categories.histogram: Creates a histogram, which shows the distribution of a set of data.errorbar: Creates a line plot with error bars at each data point.
Advanced Customization and Saving Plots
Section titled “Advanced Customization and Saving Plots”For full control over your plot’s appearance, you can get handles to graphics objects and modify their properties directly using dot notation. To save your final plot, the exportgraphics function is recommended for high-quality output.
% ... (previous plotting code) ...
% Get handle to current axes and change font sizeax = gca;ax.FontSize = 14;
% Save the current figure to a PNG fileexportgraphics(ax, 'my_beautiful_plot.png', 'Resolution', 300);