R语言 如何在ggplot注解中将空格添加到已解析的标签中?

ru9i0ody  于 2023-07-31  发布在  其他
关注(0)|答案(1)|浏览(121)

这是个奇怪的小问题。我想用变量的单位来标记一些图,但是如果我在标签上添加空格,我会得到一个错误。
例如,这个块返回一个漂亮的上标字符:

library(tidyverse)

df <- tibble(x = c(1:10), y = c(1:10))

ggplot(data = df, aes(x = x, y = y)) +
  geom_point() +
  annotate(geom = "text", x = -Inf, y = Inf, hjust = -1, vjust = 1.1,
           label = "a**2", parse = TRUE)

字符串
但是,如果我在标签上添加一个空格,例如:

ggplot(data = df, aes(x = x, y = y)) +
  geom_point() +
  annotate(geom = "text", x = -Inf, y = Inf, hjust = -1, vjust = 1.1,
           label = "Some words and a**2", parse = TRUE)


我得到:

Error in `annotate()`:
! Problem while converting geom to grob.
ℹ Error occurred in the 2nd layer.
Caused by error in `parse()`:
! <text>:1:6: unexpected symbol
1: Some words

有没有人有一个解决方案,以创建标签与空格和上标?

shyt4zoc

shyt4zoc1#

您的问题是由使用parse = TRUE引起的,这会导致annotate()函数期望标签采用数学符号,而第二个示例中的明文违反了这一点。
根据R Graphics Cookbook(一个非常有用的资源),将常规文本混合到注解中并使其正确显示的方法是使用相反类型的引号来标记纯文本部分,因此在您的情况下,如您所使用的

label = "Some words and a**2"

字符串
我们将在明文部分周围添加单引号,然后添加星号 * 以正确地显示它们彼此相邻,最后是:

label = "'Some words and '*a**2"


从而产生你所描述的理想结果。

相关问题