I want to change the color of markers in scatter plot which are greater than the specified values but I am facing difficulty
5 views (last 30 days)
Show older comments
I have the following code
But it keeps giving me the following weer
clc
clear
close all
d = 4;
N = 1000;
X = linspace(0,d,N);
func = @(X) 2*X.*cos(X.^2).*exp(sin(X.^2)) + 14;
limit = func(X);
x = 4*rand(1,N);
y = 25*rand(1,N);
figure(1),hold on
h = scatter(x,y,10,'markerfacecolor','b');
plot(X,limit,'k-','linew',1.3)
for i = 1:N
if any(y(i) < limit)
set(h,'YData','MarkerFaceColor','r','Markeredgecolor','r')
end
end
But it keeps giving me the following error
Error using matlab.graphics.chart.primitive.Scatter/set
Invalid parameter/value pair arguments.
0 Comments
Answers (2)
Walter Roberson
on 11 Apr 2022
set(h,'YData','MarkerFaceColor','r','Markeredgecolor','r')
It is possible to set YData of a scatter plot, and doing so successfully would change the Y coordinates of the markers. However, the new coordinates need to be the same kind of data as the original Y coordinates; double precision in your code. Instead, your code is trying to change the Y coordinates to instead be the character vector ['M' 'a' 'r' k' 'e' 'r' 'F' 'a' 'c' 'e' 'C' 'o' 'l' 'o' 'r']
I suspect you thought you were doing something like
set(h,'YData', y(i), 'MarkerFaceColor','r','Markeredgecolor','r') %NOT GOING TO WORK
with the intended meaning that you wanted to change the face color and edge color for the i'th point.
I would suggest
mc = repmat([0 0 1], N, 1);
h = scatter(x, y, 10, mc, 'MarkerEdgeColor', 'flat');
for i = 1:N
if y(i) < limit(x(i))
h.CData(i,:) = [1 0 0];
end
end
But if I were doing it for myself, I would vectorize the calculation and build the mc color array once, like
mask = y < limit(x);
mc = repmat([0 0 1], N, 1);
mc(mask,1) = 1; mc(mask,2) = 0; mc(mask,3) = 0;
h = scatter(x, y, 10, mc, 'MarkerEdgeColor', 'flat');
and that should build the plot the right way the first time, without needing to adjust the markers afterwards
0 Comments
See Also
Categories
Find more on Scatter Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!