MATLAB - 2D Line Plot
MATLAB - Modern 2D Line Plots
Section titled “MATLAB - Modern 2D Line Plots”A 2D line plot is one of the most fundamental and powerful tools for data visualization in MATLAB. It’s used to explore the relationship between two variables, typically by plotting data points on a Cartesian plane and connecting them with lines. Mastering plotting is essential for data analysis, reporting scientific results, and debugging algorithms.
The plot Function
Section titled “The plot Function”The core function for creating 2D plots is plot. While it has many syntaxes, modern MATLAB programming emphasizes a more readable and flexible approach using name-value pairs for customization.
Common Syntaxes
Section titled “Common Syntaxes”% 1. Basic Plottingplot(X, Y)
% 2. Plotting with Line Specification (classic shorthand)plot(X, Y, LineSpec)
% 3. Plotting with Name-Value Pairs (Modern & Recommended)plot(X, Y, 'PropertyName', PropertyValue, ...)
% 4. Plotting multiple lines at onceplot(X1, Y1, X2, Y2, ...)Explanation
Section titled “Explanation”plot(X, Y): Creates a 2D line plot of the data in vectorYversus the corresponding values in vectorX.XandYmust have the same number of elements.plot(X, Y, LineSpec): An older but still common shorthand to specify line style, marker symbol, and color. For example,'--or'specifies a dashed (--) red (r) line with circle (o) markers.plot(X, Y, 'PropertyName', PropertyValue): The recommended modern approach. It’s more explicit and readable. You can set dozens of properties like'LineWidth','Color','Marker','MarkerSize', etc. This method is far more flexible and powerful.
Example 1: A Complete, Well-Documented Plot
Section titled “Example 1: A Complete, Well-Documented Plot”A good plot is more than just a line; it has labels, a title, and is easy to read. Let’s plot a sine wave and annotate it properly.
% 1. Prepare the datax = linspace(0, 2*pi, 200); % Create 200 points from 0 to 2*pi for a smooth curvey = sin(x);
% 2. Create the plotfigure; % Create a new figure window to avoid overwriting existing plotsplot(x, y, 'LineWidth', 2); % Use a thicker line for better visibility
% 3. Annotate the plot (CRITICAL for communication)title('Sine Wave from 0 to 2π');xlabel('Angle [rad]');ylabel('Amplitude');grid on; % Add a grid for easier readingaxis([0 2*pi -1.2 1.2]); % Set axis limits for a clean lookWhen you run this code, a new figure window will appear. It will display a smooth blue sine wave that oscillates between -1 and 1. The plot will have a title, labeled x and y axes, and a grid in the background.
Example 2: Plotting Multiple Lines & Using a Legend
Section titled “Example 2: Plotting Multiple Lines & Using a Legend”To compare different datasets, you often need to plot them on the same axes. The hold on command is essential for this.
% 1. Prepare data for two functionsx = linspace(0, 2*pi, 100);y1 = sin(x);y2 = cos(x);
% 2. Plot the first linefigure;plot(x, y1, 'DisplayName', 'sin(x)', 'Color', 'blue', 'LineWidth', 2);
hold on; % Tell MATLAB to add subsequent plots to the same axes
% 3. Plot the second lineplot(x, y2, 'DisplayName', 'cos(x)', 'Color', 'red', 'LineStyle', '--', 'LineWidth', 2);
hold off; % Release the hold on the axes
% 4. Add final annotationstitle('Sine and Cosine Functions');xlabel('Angle [rad]');ylabel('Amplitude');grid on;legend('show'); % Display the legend using the 'DisplayName' propertiesThis script generates a plot with two curves: a solid blue line for the sine function and a dashed red line for the cosine function. A legend is displayed, correctly identifying which line corresponds to which function.
Example 3: Creating a Scatter Plot from Experimental Data
Section titled “Example 3: Creating a Scatter Plot from Experimental Data”Sometimes you want to show individual data points without a connecting line. This is called a scatter plot and is perfect for experimental data.
% Simulate some noisy experimental datax_data = 1:10;y_data = 2*x_data + 1 + randn(size(x_data)); % y = 2x + 1 with some noise
% Create a scatter plot using markers without a linefigure;plot(x_data, y_data, 'o', ... 'MarkerFaceColor', 'g', ... % Fill the markers with green 'MarkerEdgeColor', 'k', ... % Black edges for markers 'MarkerSize', 8); % Make markers larger
% Annotate the plottitle('Noisy Experimental Data');xlabel('Measurement ID');ylabel('Measured Value');grid on;This will produce a plot showing ten circular markers with green faces and black edges. The points will roughly follow an upward-sloping line, but with random variations, representing noise.
Practical Advice
Section titled “Practical Advice”- Always Label Your Axes: A plot without labels is meaningless.
- Use
figure: Start a new plot withfigureto avoid accidentally drawing over a previous one. - Prioritize Readability: Use name-value pairs (
'LineWidth', 2) for clarity over cryptic short-forms ('--r'). Your future self will thank you. - Save Your Work: Use
saveas(gcf, 'myPlot.png')or the more modernexportgraphics(gca, 'myPlot.pdf')to save your plot for reports and presentations.