Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split data based on column values and create scatter plot.

Tags:

r

I need to make a scatter plot for days vs age for the f group (sex=1) and make another scatter plot for days vs age for the m group (sex=2) using R.

days  age sex
 306  74   1
 455  67   2
1000  55   1
 505  65   1
 399  54   2
 495  66   2
 ...

How do I extract the data by sex? I know after that to use plot() function to create a scatter plot.

Thank you!

like image 245
Novice Avatar asked Jan 15 '23 11:01

Novice


1 Answers

You can do this with the traditional R graphics functions like:

plot(age ~ days, Data[Data$sex == 1, ])
plot(age ~ days, Data[Data$sex == 2, ])

If you prefer to color the points rather than separate the plots (which might be easier to understand) you can do:

plot(age ~ days, Data, col=Data$sex)

However, this kind of plot would be especially easy (and better looking) using ggplot2:

library(ggplot2)
ggplot(Data, aes(x=days, y=age)) + geom_point() + facet_wrap(~sex)
like image 197
David Robinson Avatar answered Jan 26 '23 04:01

David Robinson