如何在ggplot中将表达式传递给geom_text标签? (继续) [英] How to pass an expression to a geom_text label in ggplot? (Continued)

查看:119
本文介绍了如何在ggplot中将表达式传递给geom_text标签? (继续)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的

This is a follow-up my original question for how to pass an expression with subscript to a geom_text label in ggplot.

Duck geom_text()命令中使用parse = T提供了很好的解决方案.但是,我现在遇到了一个问题,因为我希望传递一个表达式来包含parse = T

Duck provided a great solution using parse = T within the geom_text() command. However, I am now running into a problem because the variable I wish to pass an expression to contains other content that appears unreadable with parse = T

这是我当前的代码(再次感谢您为此解决方案 Duck ):

Here is my current code (again, thank you to Duck for this solution):

library(ggplot2)
library(tidyverse)
#Data
my_exp <- as.character(expression('my_exp'[s][u][b]))

my_data <- 
  data.frame(
    var_1 = c("9R", "14M", "17C"),
    var_2 = c(1, 2, 3),stringsAsFactors = F
  )
#Mutate
my_data$label <- ifelse(my_data$var_1=='9R',my_exp,my_data$var_1)
#Plot
my_data %>%
  ggplot(aes(x = var_1, y = var_2))+
  geom_text(aes(label = label),parse = T)

这是我尝试渲染ggplot时出现的错误输出:

And here is the error output that appears when I try to render the ggplot:

> library(ggplot2)
> library(tidyverse)
> #Data
> my_exp <- as.character(expression('my_exp'[s][u][b]))
> my_data <- 
+   data.frame(
+     var_1 = c("9R", "14M", "17C"),
+     var_2 = c(1, 2, 3),stringsAsFactors = F
+   )
> #Mutate
> my_data$label <- ifelse(my_data$var_1=='9R',my_exp,my_data$var_1)
> #Plot
> my_data %>%
+   ggplot(aes(x = var_1, y = var_2))+
+   geom_text(aes(label = label),parse = T)
Error in parse(text = text[[i]]) : <text>:1:3: unexpected symbol
1: 14M
      ^
> 

R似乎很难读取我未通过表达式的单元格.有没有办法让R仅解析相关的单元格?

It appears R is having a hard time reading the cells where I have not passed the expression. Is there a way to have R only parse the relevant cell(s)?

谢谢!

推荐答案

或者,您可以使用ggtext包中的geom_richtext()并使用<sup>...</sup><sub>...</sub>创建上标或下标.

As an alternative, you can use geom_richtext() from the ggtext package and create super- or subscripts with <sup>...</sup> or <sub>...</sub>.

library(ggplot2)
library(ggtext)

#Data
my_exp <- "my_exp<sub>sub</sub>"

my_data <- 
  data.frame(
    var_1 = c("9R", "14M", "17C"),
    var_2 = c(1, 2, 3), stringsAsFactors = F
  )
#Mutate
my_data$label <- ifelse(my_data$var_1=='9R', my_exp, my_data$var_1)
#Plot
ggplot(my_data, aes(x = var_1, y = var_2)) +
  geom_richtext(
    aes(label = label),
    # customization to remove background and border around labels
    fill = NA,
    label.colour = NA
  )

reprex软件包(v0.3.0)创建于2020-09-09 sup>

Created on 2020-09-09 by the reprex package (v0.3.0)

这篇关于如何在ggplot中将表达式传递给geom_text标签? (继续)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆