[英]R: GGPLOT2: How do I add labels in a line graph in ggplot2 using stat_summary
[英]R: ggplot2: how to separate labels in stat_summary
我嘗試使用stat_summary
函數和我編寫的自定義函數在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_ 個元素?
有人有好的提示嗎?
我會考慮做這樣的事情:
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 = 6, show.legend = FALSE)
首先,你可以分別用means生成數據框,避免geom_bar和stat_summary的需要。 然后在將手動標簽/代碼加入到匯總數據框之后,使用 geom_text 添加它們非常簡單。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.