Plotting Multiple Data Sets on a Scatter Plot in MATLAB

Plotting Multiple Data Sets on a Scatter Plot in MATLAB

In this article, we will explore how to plot multiple data sets on a scatter plot using MATLAB.

Problem Statement
You have two sets of data, Ax and Ay, as well as Bx and By. You want to plot both data sets on a scatter plot with different colors. However, you are struggling because the scatter() function does not behave like the plot() function.

Solution

The problem arises from the way scatter() handles its input arguments. Unlike plot(), which accepts a vector of x-coordinates and a vector of y-coordinates, scatter() requires separate vectors for the x- and y-coordinates of each data set. To plot multiple data sets on a scatter plot using scatter(), you need to use the following approach:

scatter(Ax, Ay, 'g'); hold on; 
scatter(Bx, By, 'b');

In this code:

  • The first scatter() function plots the (Ax, Ay) data set with green markers ('g').
  • The hold on statement is used to preserve the current plot and prepare it for additional plotting commands.
  • The second scatter() function plots the (Bx, By) data set with blue markers ('b').

Example Code

Here's an example code snippet that demonstrates this approach:

Ax = [1 2 3; 4 5 6];
Ay = [7 8 9; 10 11 12];

Bx = [13 14 15; 16 17 18];
By = [19 20 21; 22 23 24];

figure;
scatter(Ax(:,1), Ay(:,1), 'g'); hold on;
scatter(Bx(:,1), By(:,1), 'b');

In this example, we have two data sets (Ax, Ay) and (Bx, By). We use the scatter() function to plot each data set separately, with green markers for the first data set and blue markers for the second data set.


Plotting multiple data sets on a scatter plot in MATLAB can be achieved by using the scatter() function in combination with the hold on statement. By following this approach, you can effectively visualize your data and compare trends across different data sets.

Related Articles

  • How do I connect points in a scatter plot with a line? – MATLAB Answers
  • 3D Scatter Plot in MATLAB using Scatter3 Function