2D plots are essential tools for visualizing data and functions in MATLAB. They provide a clear and intuitive way to represent relationships between variables.
The fundamental function for creating 2D plots in MATLAB is plot()
. It takes x and y coordinates as arguments and draws a line connecting the points.
x = 0:0.1:2*pi;
y = sin(x);
plot(x, y)
title('Sine Wave')
xlabel('x')
ylabel('sin(x)')
This example creates a sine wave plot with labeled axes and a title.
MATLAB offers various plot types for different data representations:
scatter()
: Creates scatter plotsbar()
: Generates bar graphshistogram()
: Displays data distributionpie()
: Shows data as a pie chartEnhance your plots with customization options:
x = linspace(0, 10, 100);
y1 = sin(x);
y2 = cos(x);
plot(x, y1, 'r--', 'LineWidth', 2)
hold on
plot(x, y2, 'b-.', 'LineWidth', 2)
legend('sin(x)', 'cos(x)')
grid on
axis([0 10 -1.5 1.5])
This example demonstrates line color, style, and width adjustments, as well as adding a legend, grid, and setting axis limits.
Use subplot()
to create multiple plots in a single figure:
x = 0:0.1:2*pi;
y1 = sin(x);
y2 = cos(x);
subplot(2,1,1)
plot(x, y1)
title('Sine')
subplot(2,1,2)
plot(x, y2)
title('Cosine')
This code creates two vertically stacked plots within one figure.
hold on
to overlay multiple plotsTo further enhance your MATLAB plotting skills, explore these related topics:
By mastering 2D plots in MATLAB, you'll be able to effectively visualize your data and communicate your findings. Practice with different plot types and customization options to create compelling and informative graphics.