sp_code <- levels(unique(df$sp_code))
for (i in seq_along(sp_code)) {
species <- sp_code[i]
plot2 <- df %>%
ggplot(aes(x=sp_code, y=ind_km2, fill=sp_code)) +
geom_violin(data = filter(df, sp_code == species), scale = "width", show.legend = FALSE) +
stat_summary(data = filter(df, sp_code == species), fun.y=mean, geom="point", shape=23, size=4, fill = "black", show.legend = FALSE)
print(plot2)
}
我想添加每个图的观测值。我已经在线搜索了解决方案,但是它们要么给我错误,要么该过滤器无法正常工作。
我尝试使用stat_summary和一个函数尝试:
# Function
add_n <- function(y, upper_limit = (df %>%
select(sp_code, ind_km2) %>%
filter(sp_code == species) %>%
summarise(mean = mean(ind_km2))) * 1.15) {
return(
data.frame(
y = 0.95 * upper_limit,
label = paste('n =', length(df), '\n')
)
)
}
# Add it to loop
for (i in seq_along(sp_code)) {
species <- sp_code[i]
plot2 <- df %>%
ggplot(aes(x=sp_code, y=ind_km2, fill=sp_code)) +
geom_violin(data = filter(df, sp_code == species), scale = "width", show.legend = FALSE) +
stat_summary(data = filter(df, sp_code == species), fun.y=mean, geom="point", shape=23, size=4, fill = "black", show.legend = FALSE)+
stat_summary(
fun.data = add_n,
geom = "text",
fun.y = median,
hjust = 0.5,
vjust = 0.9)
print(plot2)
}
这给了我一个错误(geom_text()`需要以下缺少美学:y),我在网上查找时尝试使用,但找不到对我有用的解决方案。
如何解决此错误,或者要么使用其他内容来具有我的图中每个级别的观察数?
(谢谢!)
您可以添加一个
count
facet_wrap()