I have a dataset for males and females, and I'm supposed to make a scatterplot showing the difference between women and men.
But dont know how to include separate plots for male/female. Anyone who can help me?:)
CodePudding user response:
Using par
you may set mfrow=c(1, 2)
for one row and two columns. Then plot
with subset
.
par(mfrow=c(1, 2))
plot(Deviation ~ lg_salary, subset(dat, sex == 1), col=2, main='Sex 1', ylim=range(dat$Deviation))
plot(Deviation ~ lg_salary, subset(dat, sex == 2), col=4, main='Sex 2', ylim=range(dat$Deviation))
Data:
n <- 100; set.seed(42)
dat <- data.frame(lg_salary=runif(n, 5000, 10000),
Deviation=rnorm(n),
sex=sample(1:2, replace = TRUE))
dat$Deviation[dat$sex == 1] <- dat$Deviation[dat$sex == 1] rnorm()
dat <- transform(dat, Deviation=ifelse(sex == 1, Deviation rnorm(1, 3, .5), Deviation))
CodePudding user response:
You can use the following code:
par(mfrow=c(1, 2))
plot(Deviation~lg_salary, data = subset(attractiveness_data, Female == 1), col = "pink", main = "Female", xlab = "lg salary")
plot(Deviation~lg_salary, data = subset(attractiveness_data, Female == 0), col = "blue", main = "Male", xlab = "lg salary")
Output:
Combine Female and Male in one plot
To combine them you can use the following code:
colors <- c("pink", "blue")
plot(Deviation~lg_salary, data = attractiveness_data, col = colors[factor(Female)], main = "Female vs Male", xlab = "lg salary")
legend("topleft", legend = levels(factor(attractiveness_data$Female)), pch = 19, col = colors)
Output: