A density plot is a nice alternative to a histogram
set.seed(1234)
wdata = data.frame(
sex = factor(rep(c("F","M"), each =200)),
weight = c(rnorm(200,55), rnorm(200,58))
)
library(dplyr)
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
mu <- wdata %>%
group_by(sex) %>%
summarise(grp.mean = mean(weight))
Now lets load the graphing packages
library(ggplot2)
theme_set(
theme_classic() +
theme(legend.position = "right")
)
Now lets do the basic plot function. First we will create a ggplot object
d <- ggplot(wdata, aes(x = weight))
Now lets do a basic density plot
d + geom_density() +
geom_vline(aes(xintercept = mean(weight)), linetype= "dashed")
Now lets hange the y axis to count instead of density
d + geom_density(aes(y = after_stat(count)), fill = "lightgray")+
geom_vline(aes(xintercept = mean(weight)), linetype ="dashed")
d + geom_density(aes(color = sex)) +
scale_color_manual(values = c("darkgray","gold"))
Lastly, lets fill the desity plots
d + geom_density(aes(fill = sex), alpha = 0.4) +
geom_vline(aes(xintercept = grp.mean, colr = sex), data = mu, linetype = "dashed") +
scale_color_manual(values =c("grey","gold")) +
scale_fill_manual(values = c("grey","gold"))
## Warning in geom_vline(aes(xintercept = grp.mean, colr = sex), data = mu, :
## Ignoring unknown aesthetics: colr