How can I change the color of a single data point of a scatter plot by using handles?

84 Ansichten (letzte 30 Tage)
h = scatter([x1 x2 x3; y1,y2,y3])
I have tried using the following code but it changes the the color of all the data points. I thought it would set the first point stored in the array to red instead of all the points.
set(h([1]),'CData',[1 0 0])

Akzeptierte Antwort

Mike Garrity
Mike Garrity am 11 Apr. 2016
No, the CData holds the colors of all of the points. So if there's just one color, that's going to be the color of all of the points.
What you would need to do is take the color, replicate out to the number of points, and then replace one copy. Consider this example:
npts = 5;
x = randn(1,npts);
y = randn(1,npts);
h = scatter(x,y,'filled');
c = h.CData;
% c is now a 1x3, meaning a RGB color that's used for all of the points
c = repmat(c,[npts 1]);
% c is now a 5x3 containing 5 copies of the original RGB
c(1,:) = [1 0 0];
% c now contains red, followed by 4 copies of the original color
h.CData = c;
% Now the scatter object is using those colors

Weitere Antworten (1)

Stephen23
Stephen23 am 11 Apr. 2016
Bearbeitet: Stephen23 am 11 Apr. 2016
Why just think something when you can read the documentation and know?
The function scatter return one object that represents all of the points:
s = scatter(___) returns the scatter series object.
as the documentation states, and has a link to Scatter Series Properties. There you will find the CData clearly explained:
"*CData* — Marker colors[] (default) | RGB triplet | matrix of RGB triplets | vector"
"Marker colors, specified as one of these values:"
  • "RGB triplet — Use the same color for all the markers in the plot. An RGB triplet is a three-element row vector whose elements specify the intensities of the red, green, and blue components of the color. The intensities must be in the range [0,1], for example, [0.5 0.6 0.7]."
  • "Three-column matrix of RGB triplets — Use a different color for each marker in the plot. Each row of the matrix defines one color. The number of rows must equal the number of markers."
So you tried the first version, and you actually need to try the second, something like this:
  1. get the complete matrix of all RGB triplets
  2. change the one row that you need to change
  3. set the CData with the altered matrix

Community Treasure Hunt

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

Start Hunting!

Translated by