如何组合 `geom_text` 调用的斜体和非斜体组件。将“geom_text”标签添加到一系列“facet_grid”散点图中

How to combine italic and non-italic components of a `geom_text` call. Add `geom_text` labels to a series of `facet_grid` scatter plots

我想添加一个文本标签,指示一系列 facet_wrapped 散点图(例如:"r = -0.52")的相关系数。

所以我的散点图看起来像这样:

library(tidyverse)
df <- mtcars
df %>% 
  ggplot(aes(y = mpg, x = hp)) +
  geom_point(colour = "blue") + 
  facet_grid(~ factor(cyl))

reprex package (v0.2.1)

于 2019-06-26 创建

然后我尝试创建三个单独的相关系数,分组后,我希望标签显示在图表上,但它不太正确。我希望它能这样说:"r = -0.52"

library(tidyverse)
df <- mtcars
df2 <- df %>% 
  group_by(cyl) %>% 
  summarise(correlation = cor(y = mpg, x = hp, use = "pairwise.complete.obs"))
df2
#> # A tibble: 3 x 2
#>     cyl correlation
#>   <dbl>       <dbl>
#> 1     4      -0.524
#> 2     6      -0.127
#> 3     8      -0.284
df <- left_join(df, df2, by = "cyl")

df %>% 
  ggplot(aes(y = mpg, x = hp)) +
  geom_point(colour = "blue") +
  geom_text(x = 200, y = 30, label = expression(paste(italic(r), " = ", df$correlation))) +
  facet_grid(~ factor(cyl))
#> Warning in is.na(x): is.na() applied to non-(list or vector) of type
#> 'expression'

reprex package (v0.2.1)

于 2019-06-26 创建

尝试将 geom_text 放在 facet_grid 之后,以便 R 知道将它放在哪里:

df %>% 
  ggplot(aes(y = mpg, x = hp)) +
  geom_point(colour = "blue") +
  facet_grid(~ factor(cyl)) +
geom_text(x = 200, y = 30, 
          label = paste0("italic(r) == ", round(df$correlation,2)), parse = TRUE)

你可以做到

  geom_text(x = 200, y = 30, 
            label = paste0("italic(r) == ", df$correlation), parse = TRUE) 

显示舍入相关性:

  geom_text(x = 200, y = 30, 
            label = paste0("italic(r) == ", round(df$correlation,2)), parse = TRUE)