r - ggplot : update facet labels with number of points in the plot

标签 r ggplot2 facet facet-wrap

我有一个数据集 data并且可以根据如下的要求进行绘图:

#Data
data <- data.frame(level = c(1,2,3,5,2,4,3,1,3), 
                   pay1 = c(10,21,32,12,41,21,36,14,17), 
                   pay2 = c(26,36,5,6,52,12,18,17,19))

#Plot
data %>% pivot_longer(-level) %>%
  ggplot(aes(x = name, y = value))+
  geom_boxplot() + 
  facet_wrap(~ level, scales = "free_x") +
  theme_bw()
enter image description here
我希望根据另一个变量 level 的频率更新构面标签.
table(data$level)
# 1 2 3 4 5 
# 2 2 3 1 1 
如何将 Facet 标签更新为 1 (n=2) , 2 (n=2) , 3 (n=3) , 4 (n=1) , 5 (n=1) ??

最佳答案

我只想用 mutate 重命名因子水平使用 paste 的调用和 n() :

data %>% 
  pivot_longer(-level) %>%
  group_by(level, name) %>%
  mutate(level = paste0(level, " (n = ", n(), ")")) %>%
  ggplot(aes(x = name, y = value))+
  geom_boxplot() + 
  facet_wrap(~ level, scales = "free_x") +
  theme_bw()
enter image description here

关于r - ggplot : update facet labels with number of points in the plot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64821652/

相关文章:

r - 连接 R 和 Julia?

r - 从数据框列表中合并数据框

SOLR 日期分面和 BC/BCE 日期/负日期范围

JSF 有条件地呈现页脚(jsf facet)

r - 更改 Shiny Action 按钮的颜色

r - dplyr 中的自定义 sum 函数返回不一致的结果

r - ggplot 2 - 用数值更改图例类别(无因素)

R ggplot : Two histograms (based on two different column) in one graph

r - ggplot2 中的继承有哪些限制?

hash - 过滤 Redis 哈希条目