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
xandyvectors 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
plotwithscatterโplotconnects points with lines, whilescattershows 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
| Function | Description | Example |
|---|---|---|
| scatter(x, y) | Basic scatter plot | scatter(x, y) |
| scatter(x, y, sz) | Scatter plot with marker size | scatter(x, y, 100) |
| scatter(x, y, sz, c) | Scatter plot with size and color | scatter(x, y, 50, 'r') |
| title('text') | Add title to plot | title('My Plot') |
| xlabel('text') | Label x-axis | xlabel('X values') |
| ylabel('text') | Label y-axis | ylabel('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.