aes_string是如何工作的?

How does aes_string works?

提问人:Seydou GORO 提问时间:10/17/2022 更新时间:10/17/2022 访问量:46

问:

id_data bras         Time               `Dose of estradiol`
   <chr>   <chr>        <fct>                            <dbl>
 1 16_     Progesterone Estradiol at S5-S6                588 
 2 16_     Progesterone Estradiol at S7-S8                318 
 3 16_     Progesterone Estradiol at D HCG                 43 
 4 20_     Progesterone Estradiol at S5-S6                468.
 5 20_     Progesterone Estradiol at S7-S8                470.
 6 20_     Progesterone Estradiol at D HCG                395 
 7 22_     Progesterone Estradiol at S5-S6                108 
 8 22_     Progesterone Estradiol at S7-S8                108 
 9 22_     Progesterone Estradiol at D HCG                108 
10 24_     Progesterone Estradiol at S5-S6               1369 

这是我数据集的头部 10 我想用ggplot制作一个箱线图

gplot(base_c_e2_anova_Prog, aes_string(x="Time", y= "Dose of estradiol"))+
  geom_boxplot(fill="#00AFBB")+
  labs(title = "title")

我希望我的两个变量的名称用引号括起来,因为 ggplot 应该在 a 中,两个变量 (x, y) 的名称必须用引号引起来。function()

我不知道为什么aes_string不起作用。

这是错误消息:

Error in parse(text = elt) : <text>:1:6: unexpected symbol
1: Dose of
         ^
R 函数 ggplot2 行情

评论

1赞 teunbrand 10/17/2022
与编码相关:ggplot2.tidyverse.org/articles/...aes()
0赞 Seydou GORO 10/17/2022
谢谢。这是非常有用的文档
0赞 Ronak Shah 10/17/2022
尝试使用标准列名。不建议在列名中包含空格。重命名为类似 .也已被弃用。相关 : stackoverflow.com/questions/63734097/...Dose of estradiolDose_of_estradiolaes_string
1赞 Limey 10/17/2022
“ggplot 应该在 function() 中,两个变量 (x, y) 的名称必须用引号括起来”。并非如此。@AndS。为您提供了更多详细信息。

答:

1赞 AndS. 10/17/2022 #1

我个人会避免.如果要制作一个将变量作为输入并绘制它的函数,有几种方法可以使用 。aes_stringaes

library(tidyverse)

plot_fun_no_quotes <- function(y){
  ggplot(mtcars, aes(as.factor(cyl), {{y}}))+
    geom_boxplot()
}
plot_fun_no_quotes(mpg) #correct

plot_fun_no_quotes("mpg") #incorrect

plot_fun_with_quotes <- function(y){
  ggplot(mtcars, aes(as.factor(cyl), !!sym(y)))+
    geom_boxplot()
}
plot_fun_with_quotes("mpg") #correct

plot_fun_with_quotes(mpg) #incorrect
#> Error in `sym()`:
#> ! Can't convert a <tbl_df/tbl/data.frame> object to a symbol.