I have densities of a marine species according to the year (two levels: 2020 and 2021), the protection level of the area (three levels: NP (Non-Protected), PP (Partially-Protected) and FP (Fully-Protected)) and the depth (two levels: shallow and deep). Here I show an example dataframe:
set.seed(100)
df <- data.frame(Year=as.factor(c(rep(2020,18),rep(2021,18))),
Prot=c(rep(c("NP","PP","FP"),each=6,2)),
Depth=c(rep(c("Shallow","Deep"),each=3,6)),
Density=c(runif(n = 36, min = 1, max = 20)))
str(df)
'data.frame': 36 obs. of 4 variables:
$ Year : Factor w/ 2 levels "2020","2021": 1 1 1 1 1 1 1 1 1 1 ...
$ Prot : Factor w/ 3 levels "FP","NP","PP": 2 2 2 2 2 2 3 3 3 3 ...
$ Depth : Factor w/ 2 levels "Deep","Shallow": 2 2 2 1 1 1 2 2 2 1 ...
$ Density: num 6.85 5.9 11.49 2.07 9.9 ...
I would like to make a boxplot considering the three factors mentioned, including sample points using 'geom_dotplot()'. Here I show the simplified code I am using:
Plot <- ggplot(df, aes(x=Prot, y=Density))
geom_boxplot(aes(fill=Year))
geom_dotplot(aes(fill=Year),
binaxis = "y",
binwidth=0.7,
drop=FALSE,
stackdir = "center",
dotsize = 0.5)
xlab("Protection Level")
ylab("Density")
facet_wrap(~Depth)
Plot
As you can see, the points are not properly aligned within the 'Year' factor. That is, points for the year 2020 and 2021 are all aligned together within each protection level (either 'NP', 'PP' or 'FP').
Does anyone know how to solve this?
Thanks in advance
CodePudding user response:
You could use the position argument with position_dodge:
ggplot(df, aes(x=Prot, y=Density))
geom_boxplot(aes(fill=Year))
geom_dotplot(aes(fill=Year),
binaxis = "y",
binwidth=0.7,
drop=FALSE,
stackdir = "center",
position=position_dodge(0.75),
dotsize = 0.5)
xlab("Protection Level")
ylab("Density")
facet_wrap(~Depth)


