how to change the color of the point in scatter plot while using a loop

9 views (last 30 days)
i am using scatter plot in 4 for loops once i get a particular color at some specific point.. this needs to be changed later when the condition is met at any point while the loop runs but it is showing me the color of the points once obtained..as it is. how can i make my loop work with scatter plot?

Answers (1)

Prateekshya
Prateekshya on 8 Oct 2024
Hello Supriya,
To dynamically update the color of points in a scatter plot within a loop, you need to modify the properties of the scatter plot object during each iteration. In MATLAB, the scatter function returns a scatter object that you can manipulate to change properties like color.
A general approach to achieve this is to create the scatter plot outside the loop and store the handle to the scatter object. Then use the handle to update the CData property (for color) of the scatter object based on your condition.
Here is an example code snippet illustrating this process:
% Sample data
x = rand(100, 1) * 10; % Random x data
y = rand(100, 1) * 10; % Random y data
colors = repmat([0 0 1], 100, 1); % Initial color (blue) for all points
% Create initial scatter plot
hScatter = scatter(x, y, 50, colors, 'filled'); % 50 is the marker size
% Loop through each point
for i = 1:length(x)
% Example condition: change color if x and y are both greater than 5
if x(i) > 5 && y(i) > 5
colors(i, :) = [1 0 0]; % Change color to red
end
% Update the scatter plot colors
set(hScatter, 'CData', colors);
% Pause to visualize the update (optional)
pause(0.1); % Adjust pause time as needed
end
You can modify the code according to your requirements.
I hope this helps!

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!