簡體   English   中英

更改一組堆疊條形圖中的軸標簽

[英]Changing the axis labels in a group of stacked bar charts

我有以下代碼

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 中的 soo foo 將是 'foo\\n8' 嗎? 或者是否有一種通用方法可以告訴 ggplot 在圖中的 bar/foo 標簽上方或頂部列組件的頂部邊緣上方放置一個數字?

你可以試試這個方法。 如果我錯過了什么或者我的目的有誤,請告訴我。

labels <- df2%>%
  mutate(value = as.integer(value)) %>%
  group_by(cat2, cat1) %>%
  summarize(n = sum(value))
  
labelss <- paste0(labels$cat1, "\n", labels$n)

ggplot(df2, 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)) +
  scale_x_discrete(labels = labelss) +
  facet_grid(~ cat2) 

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM