我有一个数据集,显示了不同年份不同深度发生的各种物种的计数,如下所示:
df<-data.frame(species = rep(c("A","B","C","D","E"), each = 6),
year = rep(c(2021,2022), each = 3, times = 5),
depth = rep(c(10,20,30), times = 10),
count = sample(1:10, 30, replace = TRUE),
se = runif(30, 0.1,0.9))
实际上有大约 50 个物种和 10 个地点,但我简化了我的问题。我想绘制一个条形图,其中每个深度的前 3 个最丰富的物种绘制在单独的方面。到目前为止我已经:
ggplot(head(df,3), aes(x=reorder(species, - count), y=count, fill = year)) +
geom_bar(stat="identity", position = "dodge")+
theme_bw()+
xlab("Species")+
ylab("Abundance (count +/- SE)")+
geom_errorbar(aes(ymin=count-se, ymax=count+se), width=.2,
position=position_dodge(.9))
但显然这只是绘制了整个数据帧的前 3 行,而不是每个深度的前 3 行。任何帮助将不胜感激!
我想你想要
slice_max
来自 dplyr:
library(dplyr)
library(ggplot2)
slice_max(df, order_by=count, n=3, by=depth) |>
ggplot(aes(x=species, y=count, fill = factor(year))) +
geom_bar(stat="identity", position = "dodge")+
facet_grid(~depth, scales="free", labeller=label_both)+
theme_bw()+
labs(x="Species", y="Abundance (count +/- SE)", fill="Year")+
geom_errorbar(aes(ymin=count-se, ymax=count+se), width=.2,
position=position_dodge(.9))