我有多个数据框,每个数据框来自 13 个站点,其中包含 90 个不同物种的平均丰度数据,按比例缩小后如下所示:
site1<-data.frame(species = LETTERS[1:26], abundance = sample(x = 1:10, rep = TRUE, size = 26))
site2<-data.frame(species = LETTERS[1:26], abundance = sample(x = 1:10, rep = TRUE, size = 26))
site3<-data.frame(species = LETTERS[1:26], abundance = sample(x = 1:10, rep = TRUE, size = 26))
site4<-data.frame(species = LETTERS[1:26], abundance = sample(x = 1:10, rep = TRUE, size = 26))
我想要实现的是一个条形图网格,其中按降序排列每个地点前 10 个最丰富的物种。我用的:
site1plot<-ggplot(head(site1,10), aes(x=reorder(species, - abundance), y=abundance, fill = species)) + geom_bar(stat="identity")
site2plot<-ggplot(head(site2,10), aes(x=reorder(species, - abundance), y=abundance, fill = species)) + geom_bar(stat="identity")
site3plot<-ggplot(head(site3,10), aes(x=reorder(species, - abundance), y=abundance, fill = species)) + geom_bar(stat="identity")
site4plot<-ggplot(head(site4,10), aes(x=reorder(species, - abundance), y=abundance, fill = species)) + geom_bar(stat="identity")
ggarrange(site1plot,site2plot,site3plot,site4plot, common.legend = TRUE, legend = "bottom")
我的问题是,因为不同的网站都有不同的前 10 个物种,图例并不适合所有物种,即使我可以使其包含所有物种,我需要图表对每个物种都有不同的颜色,具体取决于在订单上。如果我不做常见的图例,那么图表就会变得非常混乱,因为我有 13 个站点,并且将它们网格化并在每个站点下方都添加一个图例,这有点多了。我希望有一个简单的解决办法?非常感谢任何帮助!
我的问题是,排名前 10 的物种因地点而异,并且
要获得常见的图例,请设置填充比例的
limits=
以包括任何单个图中使用的所有物种:
set.seed(123)
library(ggplot2)
library(ggpubr)
site_data <- list(site1, site2, site3, site4) |>
lapply(\(x) x[order(x$abundance), ] |> head(10))
# Get a list of all species used in any of the plots
limits_fill <- lapply(site_data, `[[`, "species") |>
unlist() |>
unique()
site_plots <- site_data |>
lapply(\(x) {
ggplot(
x,
aes(x = reorder(species, -abundance), y = abundance, fill = species)
) +
geom_bar(stat = "identity", show.legend = TRUE) +
scale_fill_discrete(limits = limits_fill)
})
ggarrange(plotlist = site_plots, common.legend = TRUE, legend = "bottom")