gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 08:35:26 26 4
gpt4 key购买 nike

我有一个数据集 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com