I'm using this code to make boxplots:
Fecundity <- read.csv('Fecundity.csv')
FecundityPlot <- ggplot(Fecundity, aes(x=Group, Sex, y=Fecundity)) +
geom_boxplot(fill = fill, color = line) +
scale_y_continuous(name = "Fecundity") +
#scale_y_continuous(name = "Fecundity", breaks = seq(0, 80, 10), limits=c(0, 80)) +
ggtitle("Fecundity") +
theme(plot.title = element_text(hjust = 0.5))+
theme_bw(base_size = 11)
My data looks like this:
ID Group Sex Generation Fecundity Strain
ORR-100-M-01 OR-R-100 M 1 0 ORR
ORR-100-M-02 OR-R-100 M 1 0 ORR
ORR-100-M-03 OR-R-100 M 1 0 ORR
JW-100-M-01 JW-100 M 1 13 JW
JW-100-M-02 JW-100 M 1 0 JW
JW-100-M-03 JW-100 M 1 114 JW
I would like to make a boxplot with ggplot2 that has a bar for each Group and Sex. So there would be a box for Group=OR-R100 Sex=M next to OR-R100 F with Fecundity on the Y axis.
Additionally, how do I manually order the boxes so I have OR-R-20, OR-R-40, etc., in the desired order?
You can add Sex to any aes()
(color, fill, alpha etc.) within geom_boxplot()
and ggplot will automatically split out females and males in each group and dodge the boxplots, and display a legend with sex.
FecundityPlot <- ggplot(Fecundity, aes(x=Group, Sex, y=Fecundity)) +
geom_boxplot(aes(fill = Sex))
Or, if you want all of your labels on the y axis, another approach would be to make a new column concatenating group and sex, then plot using that as the x variable
Fecundity$new.group <- paste(Fecundity$Group, Fecundity Sex)
FecundityPlot <- ggplot(Fecundity, aes(x=new.group, Sex, y=Fecundity)) +
geom_boxplot()
To set a custom order for the groups, you need to make Group a factor and define the levels. Defining the order of the levels in factor()
will override the alphabetical default.
Fecundity$Group <- factor(Fecundity$Group,
levels = c("OR-R-20", "OR-R-40", "JW-100"))
Here's one way (using dplyr/tidyverse
pipes):
Fecundity %>%
mutate(Group_sex = paste(Group, Sex)) %>%
ggplot(aes(x = Group_sex, y = Fecundity)) +
geom_boxplot()
Use stringsAsFactors = FALSE
in your read.csv
call, or better yet, use the faster read_csv
from tidyverse
.
To set an order to the bars, you can use a mutate(Group_sex = factor(Group_sex, levels = c( ... ))) %>%
line after the first mutate and provide an explicit order in ...
(if the number of different combinations is small).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.