我有一组从两个不同地区的七个不同站点收集的数据。我想使用箱线图来显示站点之间和区域之间的差异。我目前有两个单独的箱形图。我正在尝试解决(但没有运气)如何在一个图中显示两者...即我希望我的图将结果显示为:站点 1、站点 2、站点 3、站点 4 ......区域1,区域 2 <- 全部在一个数字上。我在下面提供了示例数据和我当前的代码。你会注意到我的轴被翻转了——这是故意的,因为我的站点名称很长。
谢谢!
#Example script
example<-structure(list(Site = c("NS", "NS", "NS", "NE", "NE", "NE", "KO",
"KO", "KO", "MI", "MI", "MI", "KI", "KI", "KI", "HP", "HP", "HP",
"HA", "HA", "HA"), Var1 = c(30, 5, 4, 0.3, 0, 0, 48, 79, 43,
30, 30, 50, 5, 3, 3, 20, 31, 50, 30, 40, 68), Region = c("A",
"A", "A", "A", "A", "A", "A", "A", "A", "B", "B", "B", "B", "B",
"B", "B", "B", "B", "B", "B", "B")), class = "data.frame", row.names = c(NA,
-21L))
######## By Site
library(forcats)
p <- example %>%
mutate(Site = fct_relevel(Site, "HA", "HP",
"KI", "MI","KO", "NE",
"NS"
)) %>%
ggplot( aes(x=Site, y=Var1, fill = Region)) +
geom_boxplot()+xlab("Site") + ylab ("Variable 1") + ylim(0,100) +
coord_flip() + theme_bw()
plot1<- p+scale_fill_manual(values=c("#0072B2", "#D55E00")) + theme(axis.text=element_text(size=11),
axis.title=element_text(size=12))
plot1
####################### By Regions
example$Region<-factor(example$Region, levels=c("B", "A"))
pplot2<-ggplot(example, aes(x = Region, y = Var1, fill = Region)) + geom_boxplot()
pplot2<-pplot2 + ylab("Variable 1") + ylim (0,100) +
scale_x_discrete(limits = rev(levels("Region"))) + coord_flip()+ theme_bw() + scale_fill_manual(values=c("#D55E00", "#0072B2")) + theme(axis.text=element_text(size=11),
axis.title=element_text(size=12))
pplot2