'What is the R command for making a skatter plot with different variables?

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?:)



Solution 1:[1]

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))

enter image description here


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))

Solution 2:[2]

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:

enter image description here

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:

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jay.sf
Solution 2