我有以下代碼
library(tibble)
library(tidyr)
library(dplyr)
library(ggplot2)
test <- tibble(
cat1 = c(rep('foo',6),rep('bar',6)),
cat2 = rep(c('g1','g2','g3','g4','g5','g6'), 2),
zoom = rnorm(12, 0, 10),
zaps = rnorm(12, 5, 10),
buzz = rnorm(12, -5, 10)
) %>% pivot_longer(c(zoom,zaps,buzz),names_to = 'cat3', values_to='value')
test2 <- inner_join(test, summarise(group_by(test, cat1, cat2), agg = sum(value)))
ggplot(test2, aes(x = cat1, y = value, fill = cat3, label = as.integer(value)))
geom_bar(stat = 'identity', position = 'stack')
geom_text(position = position_stack(vjust = 0.5), size = 3, color = "#555555")
geom_errorbar(aes(ymin = agg, ymax = agg))
facet_grid(~ cat2)
產生以下圖表:

我喜歡這個,我對它非常滿意,但我希望在列中的某處包含每列的總和標簽(與水平黑線相同的值),最好在 x 軸上方/下方的底部標簽或在 g1,g2 下方的圖的頂部邊緣上方...我可以通過更改顯示的標簽來做到這一點,所以 g1 中的 foo 將是 'foo\n8' 嗎?或者是否有一種通用的方法可以告訴 ggplot 在圖中的 bar/foo 標簽上方或頂部列組件的頂部邊緣上方放置一個數字?
uj5u.com熱心網友回復:
你可以試試這個方法。如果我錯過了什么或者我的目的有誤,請告訴我。
df2 %>%
group_by(cat1, cat2) %>%
mutate(n = sum(as.integer(value))) %>%
rowwise %>%
mutate(cat1 = paste0(c(cat1, n), collapse = "\n")) %>%
ggplot(aes(x = cat1, y = value, fill = cat3, label = as.integer(value)))
geom_bar(stat = 'identity', position = 'stack')
geom_text(position = position_stack(vjust = 0.5), size = 3, color = "#555555")
geom_errorbar(aes(ymin = agg, ymax = agg))
facet_wrap(~ cat2, scales = "free_x", ncol = 6)

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/336889.html
上一篇:使用R查找首先滿足條件的值
