在ggplot2中使用plotmath表达式为散点添加上标标签失败求助
在ggplot2中为散点添加带右上标“+”标签的报错解决方法
问题说明
使用基础绘图的text()函数可以为散点添加带右上标“+”的表达式标签,但在ggplot2中用geom_text_repel()实现时出现报错。报错信息如下:
Don't know how to automatically pick scale for object of type <expression>. Defaulting to continuous. Error in `geom_text_repel()`: ! Problem while computing aesthetics. i Error occurred in the 2nd layer. Caused by error in `compute_aesthetics()`: ! Aesthetics are not valid data columns. x The following aesthetics are invalid: x `label = hh` i Did you mistype the name of a data column or forget to add `after_stat()`? Run `rlang::last_trace()` to see where the error occurred.
可复现代码:
library(ggrepel) library(ggplot2) data <- data.frame(x = 1:3, # 创建示例数据 y = 1:3, label = LETTERS[1:3]) data hh<-c(expression("ABC"^"+"), expression("EFG"^"+"), expression("HJK"^"+")) plot(data$x, # 基础绘图 data$y, xlim = c(1, 4)) text(data$x, # 基础绘图添加标签 data$y, labels = hh, pos = 4) ggplot(data = data,aes(x=x,y=y))+ # ggplot2报错代码 geom_point()+ geom_text_repel(aes(label = hh))
解决方法
方法1:将表达式语法存入数据框,启用解析
把带右上标的表达式以字符形式写入数据框,再通过parse=TRUE参数让ggplot2解析成数学表达式:
library(ggrepel) library(ggplot2) # 构造包含表达式字符的数据框 data <- data.frame( x = 1:3, y = 1:3, # 用单引号包裹+,避免语法冲突 label = c("ABC^'+'", "EFG^'+'", "HJK^'+'") ) ggplot(data = data, aes(x=x, y=y)) + geom_point() + geom_text_repel(aes(label = label), parse = TRUE)
方法2:直接存入表达式列表列
如果要保留expression()对象,可以将其作为列表列加入数据框,同样配合parse=TRUE使用:
library(ggrepel) library(ggplot2) data <- data.frame( x = 1:3, y = 1:3 ) # 添加表达式列表作为数据框列 data$label <- list(expression("ABC"^"+"), expression("EFG"^"+"), expression("HJK"^"+")) ggplot(data = data, aes(x=x, y=y)) + geom_point() + geom_text_repel(aes(label = label), parse = TRUE)
报错原因
原代码直接将外部表达式向量hh传入aes(label = hh),但ggplot2的美学映射默认要求关联数据框内的列,且无法自动识别外部表达式向量的类型。将表达式整合到数据框并启用解析,即可解决该问题。
内容的提问来源于stack exchange,提问作者Charité Learner
相关产品推荐
相关产品推荐

