How can I color a (circle) area in a scatterplot?

6 ビュー (過去 30 日間)
Anna Boehm
Anna Boehm 2018 年 10 月 1 日
回答済み: Anna Boehm 2018 年 10 月 2 日
In my task, I should draw n samples from a two dimensional random variable U=(U1,U2), where U1 and U2 are independent and both uniformly distributed on [-1,1].
Afterwards, I should plot the sample and mark all the samples which fulfill (U1^2 + U2^2)<1. (I already know that the outcome will be a circle with radius r=1.)
To plot the sample I used scatter(U1,U2). How can I color the samples which fulfill the condition (U1^2 + U2^2)<1?

回答 (4 件)

Adam
Adam 2018 年 10 月 1 日
doc scatter
shows a 4-argument syntax which allows you to include a vector of colours of equal length to the x and y. So you can use whatever logic you wish to make some of those colours different and the rest a standard colour. In your case just a simple logical mask can be used to insert your chosen colour into an array of your chosen default colour.
You can pass in [] as the 3rd argument if you don't care about explicitly setting the marker size.

jonas
jonas 2018 年 10 月 1 日
編集済み: jonas 2018 年 10 月 1 日
You could do something like,
id=(U1.^2+U2.^2)<1;
plot(U1(id),U2(id),'.r',U1(~id),U2(~id),'.k')

JohnGalt
JohnGalt 2018 年 10 月 1 日
I don't have access to the scatterplot function but the technique you're looking for is called logical indexing... where you set up an index for each co-ordinate which is either true or false. if it's true plot it one colour, if it's false plot it another colour.
samples = rand(10000,2)*2 -1; % create data
x = samples(:,1);
y = samples(:,2);
mask = (x.^2 + y.^2) <1; % create logical mask (true/false)
figure; hold on; % new figure window. enable overlaying of plots
plot(x,y,'b.'); % plot a blue dot for all points
plot(x(mask),y(mask),'r.') % overwrite all points where mask==true with a red dot

Anna Boehm
Anna Boehm 2018 年 10 月 2 日
Thanks to all, it works perfectly!

カテゴリ

Help Center および File ExchangeScatter Plots についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by