在图标题中使用数据框变量名称

问题描述 投票:1回答:1

我有一个包含多个变量的数据框,我希望将其标记,然后在几个ggplots中使用。我使用labeller包使用以下代码应用标签。

library(tidyverse)
library(labeller)
library(ggpubr)

example.df <- data.frame( 
origin = sample(c("hum_1", "mou_1"), 100, replace = TRUE),
v1 = rnorm(100, 100, 5), 
v2 = rnorm(100, 10,5), 
v3 = rnorm (100, 25, 5))

example.df <- example.df %>% set_variable_labels(origin = "original sample", v1 = "effect of Rx", v2 = "response", v3 = "weight (kg)")

这会使标签显示在数据框中。但是,当我使用ggqqplotggpubr绘制这些变量时,我没有在结果图中看到标签。

vars <- dput(colnames(select_if(example.df, is.numeric)))

lapply(vars, function(item) {
   ggqqplot(example.df, x=item, combine = FALSE, facet.by = "origin")+
   ggtitle(item)
   }
)

enter image description here enter image description here enter image description here

我想有原始样本,rx和重量(kg)的效果显示而不是v1,v2和v3。任何帮助深表感谢。谢谢。

r ggplot2 label plotmath ggpubr
1个回答
1
投票

你可以给vars命名,然后使用map2()包中的imap()purrr函数来循环它们。要包含上标/下标/数学符号,请将expression()parse(text = ...)一起使用(另请参阅这些example1example2)。

names(vars) <- c(expression('effect of Rx'^{1}), 
                 "response", 
                 expression(weight/individual %.% kg[2])
                 )
vars
#>  "effect of Rx"^{\n    1\n}                    response 
#>                        "v1"                        "v2" 
#> weight/individual %.% kg[2] 
#>                        "v3"

### from purrr package
map2(vars, names(vars), ~ ggqqplot(example.df, x = .x, combine = FALSE, facet.by = "origin") +
       ggtitle(parse(text = .y)))

# or `imap(x, ...)` which is short hand for map2(x, names(x), ...) 
imap(vars, ~ ggqqplot(example.df, x = .x, combine = FALSE, facet.by = "origin") +
       ggtitle(parse(text = .y)))


#> $`"effect of Rx"^{\n    1\n}`

#> 
#> $response

#> 
#> $`weight/individual %.% kg[2]`

reprex package创建于2019-03-11(v0.2.1.9000)

© www.soinside.com 2019 - 2024. All rights reserved.