I want to change the color of the markers in scatter plot which are below the function line
1 次查看(过去 30 天)
显示 更早的评论
I have the following code
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 the following error
Error using matlab.graphics.chart.primitive.Scatter/set
Invalid parameter/value pair arguments.
Any help would be appreciated
采纳的回答
Star Strider
2022-4-11
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
scatter(x,y,10,'markerfacecolor','b');
Lv = y < func(x); % Logical Vector Based On 'func' Value At Each 'x'
scatter(x(Lv),y(Lv),10,'MarkerFaceColor','r','Markeredgecolor','r')
plot(X,limit,'k-','linew',1.3)
.
2 个评论
Star Strider
2022-4-11
Thank you!
Sure!
The ‘Lv’ variable is a logical vector that calculates the value of ‘func’ at each ‘x’ value and compares that result with the corresponding ‘y’ value. If that ‘y’ value is less than ‘func(x)’, that value of ‘Lv’ is set to true. (It definitely helps that ‘func’ is an anonymous function in your original code, making this straightforward.)
The scatter call just after that uses ‘Lv’ to refer to the individual ‘x’ and ‘y’ values, plotting only those that are true as defined by ‘Lv’.
更多回答(1 个)
MJFcoNaN
2022-4-11
You can try this:
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);
ind_r = y < limit;
c=zeros(N,3);
% red
c(ind_r, 1)=1;
% blue
c(~ind_r, 3)=1;
figure(1),hold on
h = scatter(x,y,10,c);
plot(X,limit,'k-','linew',1.3)
2 个评论
MJFcoNaN
2022-4-11
Why do you make both x and y random?
If your task allows one random value, for example x=X, it may give out a more "reasonable" result, which achieves the same algorithm as the other answer.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Scatter Plots 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!