How to make 2D plot of points with different colors?

Click For Summary
SUMMARY

This discussion focuses on creating a 2D scatter plot in MATLAB where points are colored based on a separate variable. The user initially attempted to use the 'plot' function but encountered issues. By switching to the 'scatter' function, as recommended in a referenced article, the user successfully implemented color differentiation based on the values of a variable represented by 1 (red) and -1 (blue). The final working code utilizes the 'scatter' function with the appropriate color matrix.

PREREQUISITES
  • Understanding of MATLAB programming
  • Familiarity with 2D plotting functions in MATLAB
  • Knowledge of color representation in MATLAB graphics
  • Basic concepts of vector manipulation in MATLAB
NEXT STEPS
  • Explore MATLAB's 'scatter3' function for 3D plotting
  • Learn about MATLAB's color maps for advanced color customization
  • Investigate data visualization techniques using MATLAB's 'plot' and 'scatter' functions
  • Review MATLAB documentation on vectorized operations for performance optimization
USEFUL FOR

Data scientists, MATLAB users, and anyone interested in visualizing data points with conditional formatting in MATLAB.

kelvin490
Gold Member
Messages
227
Reaction score
3
I want to make a 2D plot of points with different x, y coordinates and have colors depending on a separate variable. I have make column vectors for x and y coordinates and another column containing 1 or -1. I would like to represent the points with 1 as red and -1 as blue points. I have codes as follow:
Matlab:
x_dis=rho_rec(1:nDis,xCol,step);%x coordinates
y_dis=rho_rec(1:nDis,yCol,step); %y coordinates
bv=rho_rec(1:nDis,bvCol,step); % 1 or -1

for i=1:1:nDis
   if bv(i)==1
        dis_color(i,1:3)=[0 0 1]; %blue
    elseif bv(i)==-1
        dis_color(i,1:3)=[1 0 0]; %red
    end
end

plot(x_dis,y_dis,'.','Color',dis_color(1:nDis,:))

However it doesn't work. How should I modify the code? Thank you.
 
Last edited by a moderator:
Physics news on Phys.org
I have changed to use scatter instead of plot, as suggested by other
So the command becomes:

scatter(x_dis,y_dis,[],dis_color(1:nDis,:),'.')

It works like a charm
 

Similar threads

  • · Replies 8 ·
Replies
8
Views
3K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 3 ·
Replies
3
Views
7K
  • · Replies 1 ·
Replies
1
Views
2K
Replies
2
Views
3K
  • · Replies 2 ·
Replies
2
Views
4K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 4 ·
Replies
4
Views
3K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 11 ·
Replies
11
Views
4K