0
0
MatlabHow-ToBeginner ยท 3 min read

How to Create Scatter Plot in MATLAB: Simple Guide

To create a scatter plot in MATLAB, use the scatter(x, y) function where x and y are vectors of data points. This plots points on a 2D plane showing the relationship between x and y.
๐Ÿ“

Syntax

The basic syntax for a scatter plot in MATLAB is scatter(x, y). Here, x and y are vectors of the same length representing the coordinates of points. You can also customize the marker size and color using optional arguments.

  • x: Vector of x-coordinates.
  • y: Vector of y-coordinates.
  • sz (optional): Marker size.
  • c (optional): Marker color.
matlab
scatter(x, y)
scatter(x, y, sz)
scatter(x, y, sz, c)
๐Ÿ’ป

Example

This example shows how to create a simple scatter plot with 20 random points. It also demonstrates how to change marker size and color.

matlab
x = randn(20,1);
y = randn(20,1);
scatter(x, y, 100, 'r', 'filled');
title('Scatter Plot Example');
xlabel('X values');
ylabel('Y values');
Output
A scatter plot window opens showing 20 red filled circles scattered randomly around the origin.
โš ๏ธ

Common Pitfalls

Common mistakes include:

  • Using x and y vectors of different lengths, which causes an error.
  • Not specifying marker size or color correctly, leading to default small black dots that are hard to see.
  • Confusing plot with scatter โ€” plot connects points with lines, while scatter shows individual points.
matlab
x = 1:5;
y = [2, 3]; % Wrong length
scatter(x, y) % This will cause an error

% Correct way:
y = [2, 3, 4, 5, 6];
scatter(x, y, 50, 'b', 'filled')
Output
Error due to vector length mismatch; corrected code produces a blue scatter plot with filled markers.
๐Ÿ“Š

Quick Reference

FunctionDescriptionExample
scatter(x, y)Basic scatter plotscatter(x, y)
scatter(x, y, sz)Scatter plot with marker sizescatter(x, y, 100)
scatter(x, y, sz, c)Scatter plot with size and colorscatter(x, y, 50, 'r')
title('text')Add title to plottitle('My Plot')
xlabel('text')Label x-axisxlabel('X values')
ylabel('text')Label y-axisylabel('Y values')
โœ…

Key Takeaways

Use scatter(x, y) to plot points where x and y are equal-length vectors.
Customize marker size and color with additional arguments for better visuals.
Ensure x and y vectors have the same length to avoid errors.
Use title, xlabel, and ylabel to add descriptive labels to your plot.
Remember scatter plots show points without connecting lines, unlike plot.