Skip to content
MATLAB

2D Plotting

Create line plots with labels, legends, and styling.

By EZ4Code Team
plotvisualization

Code

x = linspace(0, 2*pi, 100);
y1 = sin(x);
y2 = cos(x);

figure;
plot(x, y1, 'b-', 'LineWidth', 2); hold on;
plot(x, y2, 'r--', 'LineWidth', 2);

xlabel('x');
ylabel('y');
title('Sine and Cosine');
legend('sin(x)', 'cos(x)');
grid on;

% Save
saveas(gcf, 'plot.png');

% Subplots
subplot(2, 1, 1); plot(x, y1); title('Sin');
subplot(2, 1, 2); plot(x, y2); title('Cos');

Explanation

hold on keeps the current plot so you can overlay multiple lines. Use subplot for multi-panel figures. Line styles are specified by strings like 'b-' (blue solid) or 'r--' (red dashed). saveas exports to image files.

More MATLAB Snippets