解决R修改数据列名后ggplot绘图报错及图例显示问题
修改带空格列名后ggplot绘图报错的解决方法
直接把列名改为Standard deviation后绘图报错,核心原因是含空格的列名不能直接在ggplot的aes()里裸写,R无法识别这种格式的变量名。下面是几种可行的解决思路:
方法1:修改列名后用反引号包裹列名
先完成列名修改,然后在aes()里用反引号把带空格的列名包起来,让R正确识别:
# 修改列名 colnames(df1)[3] <- "Standard deviation" # 调整绘图代码,用反引号包裹含空格的列名 plot <- ggplot(df1, aes(x, y, linetype = `Standard deviation`)) + geom_line() + theme(plot.title = element_text(size = 10, face = "bold", lineheight=1.5), legend.text=element_text(size=12), legend.position = c(.6, .5), legend.justification = c("right", "center"), legend.box.just = "center", legend.margin = margin(6, 6, 6, 6))
方法2:用dplyr重命名列(更直观)
如果习惯tidyverse语法,用rename()函数重命名列,绘图时同样用反引号引用:
library(dplyr) # 重命名列,替换掉点号 df1 <- df1 %>% rename(`Standard deviation` = Standard.deviation) # 绘图代码和方法1一致 plot <- ggplot(df1, aes(x, y, linetype = `Standard deviation`)) + geom_line() + theme(plot.title = element_text(size = 10, face = "bold", lineheight=1.5), legend.text=element_text(size=12), legend.position = c(.6, .5), legend.justification = c("right", "center"), legend.box.just = "center", legend.margin = margin(6, 6, 6, 6))
方法3:用.data代词引用列名
不需要写反引号的替代方式,使用.data代词通过字符串索引调用列:
plot <- ggplot(df1, aes(x, y, linetype = .data[["Standard deviation"]])) + geom_line() + theme(plot.title = element_text(size = 10, face = "bold", lineheight=1.5), legend.text=element_text(size=12), legend.position = c(.6, .5), legend.justification = c("right", "center"), legend.box.just = "center", legend.margin = margin(6, 6, 6, 6))
以上方法都能让图例自动显示Standard deviation(不带点号),同时避免绘图报错。
内容的提问来源于stack exchange,提问作者Rustam
相关产品推荐
相关产品推荐

