我有一個海洋物種的密度按年份(兩個級別:2020 年和 2021 年),該區域的保護級別(三個級別:NP(未受保護)、PP(部分受保護)和 FP(完全受保護)) )和深度(兩個級別:淺和深)。這里我展示了一個示例資料框:
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 ...
考慮到提到的三個因素,我想制作一個箱線圖,包括使用“geom_dotplot()”的樣本點。在這里,我展示了我正在使用的簡化代碼:
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

如您所見,這些點在“年份”因子內未正確對齊。也就是說,2020 年和 2021 年的點在每個保護級別(“NP”、“PP”或“FP”)內都對齊。
有誰知道如何解決這個問題?
提前致謝
uj5u.com熱心網友回復:
您可以使用以下position引數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)

轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/406990.html
標籤:
