Home > Back-end >  density plot based based on group
density plot based based on group

Time:09-06

I'd like to make a density plot of wages by marrital status (married/not married). This is what I have, but it's only providing a density plot for one variable.

nls80 = read.csv('https://raw.githubusercontent.com/bandcar/Examples/main/nls80(1).csv')
library(ggplot2)
ggplot(nls80, aes(x = wage, colour = married))  
  geom_density()

Suggestions on a fix?

CodePudding user response:

colour accepts character and factor, but not numeric columns:

ggplot(nls80, aes(x = wage, colour = factor(married)))  
  geom_density()

enter image description here

CodePudding user response:

Here is a base R solution for multiple variables.

par(mfrow=c(2, 2))
lapply(names(iris2)[-5], \(x) {
       d <- by(iris2[[x]], iris2$Species, density, from=min(iris2[[x]]), max(iris2[[x]]))
       plot(d[[1]], main=x, col=2); lines(d[[2]], col=4)
       legend('topright', leg=unique(iris2$Species), col=c(2, 4), lty=1, cex=.8)
       })

enter image description here


Data:

iris2 <- iris[iris$Species %in% c('setosa', 'versicolor'), ]
  • Related