aes_string函数失效排查:ggplot带空格变量箱线图绘制报错
问题描述
我的数据集前10行如下:
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
我想用ggplot绘制箱线图,代码如下:
ggplot(base_c_e2_anova_Prog, aes_string(x="Time", y= "Dose of estradiol"))+ geom_boxplot(fill="#00AFBB")+ labs(title = "title")
由于这段代码需要嵌入到function()中,x、y变量名必须以字符串形式传入,但aes_string函数无法正常工作,报错信息如下:
Error in parse(text = elt) : <text>:1:6: unexpected symbol 1: Dose of ^
问题原因
aes_string的工作逻辑是把传入的字符串解析为R代码,而你的y变量名"Dose of estradiol"包含空格,直接传入时R解析器会将其拆分为多个独立符号(Dose、of、estradiol),触发语法错误。
解决方案
方法1:用反引号包裹带空格的变量名字符串
给带空格的变量名加上反引号,让R解析器识别为单个变量:
ggplot(base_c_e2_anova_Prog, aes_string(x="Time", y= "`Dose of estradiol`"))+ geom_boxplot(fill="#00AFBB")+ labs(title = "title")
方法2:改用.data代词(推荐)
从ggplot2 3.0.0版本开始,官方更推荐使用.data代词处理字符串形式的变量名,比aes_string更稳定且符合现代ggplot2语法:
ggplot(base_c_e2_anova_Prog, aes(x = .data[["Time"]], y = .data[["Dose of estradiol"]]))+ geom_boxplot(fill="#00AFBB")+ labs(title = "title")
方法3:重命名变量(一劳永逸)
如果后续会频繁使用该变量,可以先重命名数据集里的变量,去掉空格避免后续麻烦:
# 重命名变量 base_c_e2_anova_Prog <- base_c_e2_anova_Prog %>% rename(Dose_of_estradiol = `Dose of estradiol`) # 使用新变量名绘图 ggplot(base_c_e2_anova_Prog, aes_string(x="Time", y= "Dose_of_estradiol"))+ geom_boxplot(fill="#00AFBB")+ labs(title = "title")
内容的提问来源于stack exchange,提问作者Seydou GORO
相关产品推荐
相关产品推荐

