我尝试使用stat_summary
函数和我编写的自定义函数在条形上方绘制标签。一共有三个条,每个条分别标有字母a:c。但是,不是将每个标签放置一个标签,而是将所有三个标签都放置在彼此的顶部:
codes <- c ("a", "b", "c")
simple_y <- function(x) {
return (data.frame (y = mean (x) + 1, label = codes))
}
ggplot (iris, mapping = aes (x = Species, y = Sepal.Length)) +
geom_bar (stat = "summary", fun.y = "mean", fill = "blue", width = 0.7, colour = "black", size = 0.7) +
stat_summary (fun.data = simple_y, geom = "text", size = 10)
我确实理解了为什么它不起作用:每次循环simply_y
函数时,它都会看到整个codes
-向量。但是,我不知道如何告诉R分隔三个标签。回收一个函数时是否可以告诉R随后使用输入向量的n_th个元素?
有人有很好的提示吗?
我会考虑做这样的事情:
labels <-
tibble(
Species = factor(c("setosa", "versicolor", "virginica")),
codes = c("a", "b", "c")
)
iris %>%
group_by(Species) %>%
summarize(Mean = mean(Sepal.Length)) %>%
ungroup() %>%
left_join(labels, by = "Species") %>%
ggplot(aes(x = Species, y = Mean)) +
geom_col(fill = "blue", width = 0.7, color = "black", size = 0.7) +
geom_text(aes(y = Mean + 0.3, label = codes, size = 10), show.legend = FALSE)
首先,您可以使用均值分别生成数据帧,而无需geom_bar和stat_summary。然后,在将手动标签/代码添加到该汇总数据框中之后,很容易用geom_text添加它们。