set.seed(1234)
wdata=data.frame(
sex = factor(rep(c("F","M"),each = 200)),
weight = c(rnorm(200,56),rnorm(200,58))
)
head(wdata,4)
## sex weight
## 1 F 54.79293
## 2 F 56.27743
## 3 F 57.08444
## 4 F 53.65430
Now let load dplyr
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 plotting package
library(ggplot2)
theme_set(
theme_classic() +
theme(legend.position ="bottom")
)
Now lets create a ggplot object
a <- ggplot(wdata, aes(x = weight))
a + geom_histogram(bins = 30, color = "black",fill="grey") +
geom_vline(aes(xintercept = mean(weight)),
linetype ="dashed",size = 0.6 )
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
Now lets change the color by group
a + geom_histogram(aes(color = sex), fill="white", position = "identity")+
scale_color_manual(values= c("#00AFBB","#E7B800"))
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
a + geom_histogram(aes(color = sex, fill=sex), position = "identity")+
scale_color_manual(values= c("#00AFBB","#E7B800")) +
scale_fill_manual(values = c("indianred","lightblue1"))
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
What if we want to combine density plot and histograms?
a + geom_histogram(aes(y = stat(density)),
color = "black", fill = "white") +
geom_density(alpha = 0.2, fill = "#FF6666")
## Warning: `stat(density)` was deprecated in ggplot2 3.4.0.
## ℹ Please use `after_stat(density)` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
a + geom_histogram(aes(y = stat(density), color = sex),
fill = "white", position = "identity")+
geom_density(aes(color = sex), size = 1) +
scale_color_manual(values = c("indianred","lightblue1"))
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.