df <- data.frame(dose = c("D0.5", "D1", "D2"),
len = c(4.2, 10, 29.5))
df
## dose len
## 1 D0.5 4.2
## 2 D1 10.0
## 3 D2 29.5
Second dataframe
df2 <- data.frame(supp=rep(c("VC", "OJ"), each = 3),
dose = rep(c("D0.5","D1","D2"),2),
len = c(6.8, 15, 33, 4.2, 10, 29.5))
df2
## supp dose len
## 1 VC D0.5 6.8
## 2 VC D1 15.0
## 3 VC D2 33.0
## 4 OJ D0.5 4.2
## 5 OJ D1 10.0
## 6 OJ D2 29.5
Lets load up ggplot2
library(ggplot2)
Lets set our parameters for ggplot
theme_set(
theme_classic() +
theme(legend.position = "top")
)
Lets start with some basic barplots using the tooth data
f <- ggplot(df, aes(x=dose,y=len))
f + geom_col()
f + geom_col(fill="darkblue") + geom_text(aes(label=len), vjust=-0.3)
f+geom_col(fill ="darkblue")+geom_text(aes(label = len),vjust=1.6,color="white")
Now lets change the barplot colors by group
f+geom_col(aes(color=dose),fill ="white")+scale_color_manual(values=c("blue","gold","red"))
This is kinda hard to see, so lets change the fill.
f+geom_col(aes(fill =dose))+scale_color_manual(values=c("blue","gold","red"))
Ok how do we do this with multiple groups
ggplot(df2,aes(x=dose,y=len))+
geom_col(aes(color=supp,fill=supp),position=position_stack())+
scale_color_manual(values=c("blue","gold"))+
scale_fill_manual(values = c("blue","gold"))
p <- ggplot(df2,aes(x=dose,y=len))+
geom_col(aes(color=supp,fill=supp),position = position_dodge(0.8), width=0.7)+
scale_color_manual(values=c("blue","gold"))+
scale_fill_manual(values = c("blue","gold"))
p
Now lets add those labels to the dodged barplot
p+geom_text(
aes(label=len,group=supp),
position = position_dodge(0.8),
vjust=-0.3,size=3.5
)
Now wht if we want to add labels t oour stacked barplots? For this we
need 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
df2 <- df2 %>%
group_by(dose) %>%
arrange(dose,desc(supp)) %>%
mutate(lab_ypos = cumsum(len)-0.5*len)
df2
## # A tibble: 6 × 4
## # Groups: dose [3]
## supp dose len lab_ypos
## <chr> <chr> <dbl> <dbl>
## 1 VC D0.5 6.8 3.4
## 2 OJ D0.5 4.2 8.9
## 3 VC D1 15 7.5
## 4 OJ D1 10 20
## 5 VC D2 33 16.5
## 6 OJ D2 29.5 47.8
Now lets recreate our stacked graphs
ggplot(df2,aes(x=dose,y=len))+
geom_col(aes(fill=supp),width=0.7)+
geom_text(aes(y=lab_ypos, label=len,group=supp),color="white")+
scale_color_manual(values=c("blue","gold"))+
scale_fill_manual(values = c("blue","gold"))