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

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

问题描述

我试图将带下标的表达式传递给ggplot中的单个geom_text()标签.这是我现在的代码:

I am attempting to pass an expression with subscript to a single geom_text() label in ggplot. Here is my code right now:

my_exp <- expression('my_exp'[s][u][b])

my_data <- 
  data.frame(
    var_1 = c("a", "b", "c"),
    var_2 = c(1, 2, 3)
  )

my_data %>%
  ggplot(aes(x = var_1, y = var_2))+
  geom_text(aes(label = var_1))

这是结果图:

我想做的是用my_exp指定的表达式替换"a"var_1值,然后让geom_text()将该值作为表达式求值,导致下标出现在ggplot上.

What I would like to do is replace the var_1 value of "a" with the expression specified by my_exp and then have geom_text() evaluate that value as an expression, resulting in the subscript appearing on the ggplot.

推荐答案

我建议采用这种方法.您可以为标签构建另一个变量,然后启用geom_text()中的选项parse=T,以获得所需的图.这里的代码:

I would suggest this approach. You can build another variable for your labels and then enable the option parse=T from geom_text() in order to have the desired plot. Here the code:

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

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

输出:

更新:如果此处的标签有问题,请使用相应的代码

Update: If there are issues with labels here a code for that:

#Label
my_exp <- "14~M~my_exp[s][u][b]"
#Code
my_data <- 
  data.frame(
    var_1 = c("a", "b", "c"),
    var_2 = c(1, 2, 3),stringsAsFactors = F
  )
#Mutate
my_data$label <- ifelse(my_data$var_1=='a',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中将表达式传递给geom_text标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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