我想添加一个文本标签,该标签指示一系列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创建
答案 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)