如何合并`geom_text`调用的斜体和非斜体部分。在一系列facet_grid散点图中添加`geom_text`标签

时间:2019-06-26 07:37:11

标签: r ggplot2 tidyverse facet-grid geom-text

我想添加一个文本标签,该标签指示一系列facet_wrap ped散点图上的相关系数(例如:“ 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创建

2 个答案:

答案 0 :(得分:3)

你可以

  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) 

答案 1 :(得分:1)

尝试将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)

enter image description here