带有下标和变量源的标签或注释

时间:2014-06-20 17:37:07

标签: r ggplot2

我有一个R例程,它从一大组数据中创建了许多图。每个图都标有描述所绘制的点集细节的标题。不幸的是,如果我使用粘贴来组合复杂的标签,我就无法在文本中使用下标。结果很难看。这是使用R数据的代码的简化版本。标题显示了我目前使用的技术,没有下标。对改进版本的尝试放在x轴上或绘图上。

library(ggplot2)
x1 = 1
x2 = 2
list <- c(1:4)
tle <- paste("VGM = ", as.character(list[1]),
         "V, VDM = ", as.character(list[2]),
         "V, VGF = ", as.character(list[3]),
         "V, VDF = ", as.character(list[4]),
         "V", sep="")
p <- ggplot(mtcars, aes(x=wt, y=mpg)) +
  labs(title=tle) +
  geom_point()
p
p + xlab(expression(V[DM]))  #works fine
p + xlab(expression(paste(V[DM], "= 3"))) # works fine

# now we would like to use a variable to provide the number

p + xlab(expression(paste(V[DM], "=", x1))) # Just displays "x1", not value of x1
p + xlab(expression(paste(V[DM], "=", 
                      as.character(x1)))) # NO
p + xlab(expression(paste(V[DM], "=", 
                      as.character(as.number(x1))))) # NO
my.xlab1 <- bquote(V[DM] == .(x1)) 
p + xlab(my.xlab1) # We can see the success here

# A single variable at the end of the expression works
# What if you wanted to display two variables?

my.xlab2 <- bquote(V[GM] == .(x2))
my.xlab3 <- paste(my.xlab1, my.xlab2) 
p + xlab(my.xlab3) # doesn't work

# Apparently the expressions cannot be pasted together. Try another approach.
# Place the two expressions separately on the plot. They no longer need to be
# pasted together. It would look better, anyway. Would it work?

p + annotate("text", x=4, y=30, label="Annotate_text", parse=TRUE) 
# This is the idea
# p + annotate("text", x=4, y=30, label=bquote(V[DM] == .(x1)), parse=TRUE) 
# This is a disaster
# RStudio stops the process with a question mark placed on the console. Appears that
# more input is being requested?
p + geom_text(x=4, y=30, label="Geom_text") # works
p + geom_text(x=4, y=30, label=my.xlab1) # does not accept variables.

我收录的评论描述了每次尝试引发的问题。理想情况下,信息应该作为注释放在情节而不是标题上,但我找不到办法来做到这一点。使用下标将一个字符转换为一个表达式,似乎有一长串函数列表处理字符而不是表达式。

1 个答案:

答案 0 :(得分:3)

如果你想&#34;粘贴&#34;两个表达式在一起,你需要有一些&#34;运算符&#34;加入他们。确实没有表达式的粘贴方法,但有一些方法可以将它们组合在一起。首先,显然你可以使用一个bquote()将两个变量放在一起。任

my.xlab3 <- bquote(V[DM] == .(x1)~ V[GM] == .(x2))
my.xlab3 <- bquote(list(V[DM] == .(x1), V[GM] == .(x2)))

会奏效。第一个在它们之间放置一个空格,第二个在它们之间加一个逗号。但是如果你想单独构建它们,你可以将它们与另一轮bquote结合起来。所以上面两个表达式的等效构建方法是

my.xlab3 <- bquote(.(my.xlab1) ~ .(my.xlab2))
my.xlab3 <- bquote(list(.(my.xlab1), .(my.xlab2)))

所有这些都应该可以设置xlab()值。

现在,如果您还想要注释工作,您可以&#34;解析&#34;你的表达,然后让R&#34;重新解析&#34;它适合你,你应该全力以赴。观察

p + annotate("text", x=4, y=30, label=deparse(my.xlab3), parse=TRUE)