使用ggpubr Stat_cor以粗体显示相关系数

k4ymrczo  于 9个月前  发布在  其他
关注(0)|答案(1)|浏览(95)

我使用stat_cor()在箱线图上显示Pearson相关系数。为了便于系数的可见性,我试图用粗体显示它们。我对R还很陌生,我试图用以下代码自己解决这个问题:

ggplot(iris, aes(x = Sepal.Width, y = Sepal.Length)) +
  geom_point(aes(color = Species)) +
  stat_smooth(method = lm, aes(color = Species), se = FALSE) +
  stat_cor(aes(color = Species, label = after_stat(r.label)), 
  r.accuracy = 0.01, label.x = 4, label.y = c(8, 7.8, 7.6), 
  fontface = "bold") +
  scale_color_manual(values = c("grey70", "gold", "green3")) +
  theme_classic() +
  theme(
        legend.background = element_rect(fill="grey90", 
                                         size=0.5, linetype="solid"))

字符串
这个方法不起作用,我不知道如何在theme()中实现它,尽管我相信可能有一种方法。

egmofgnx

egmofgnx1#

一般来说:theme()对文本标签没有影响。它设置图的整体外观,只影响所谓的非数据墨迹。对于文本标签,您必须在geom或stat中设置字体。但是,stat_cor使用?plotmath表达式来创建标签,也就是说,使R或.斜体。并且在标签的表面不能通过fontface=设置或更改。
因此,要使标签加粗,需要在after_stat中自己创建标签:

library(ggplot2)
library(ggpubr)

ggplot(iris, aes(x = Sepal.Width, y = Sepal.Length)) +
  geom_point(aes(color = Species)) +
  stat_smooth(method = lm, aes(color = Species), se = FALSE) +
  stat_cor(
    aes(
      color = Species,
      label = after_stat(
        paste0(
          "bolditalic(R)~",
          "bold(`=`)~",
          "bold('", r, "')"
        )
      )
    ),
    r.accuracy = 0.01,
    label.x = 4, label.y = c(8, 7.8, 7.6),
  ) +
  scale_color_manual(values = c("grey70", "gold", "green3")) +
  theme_classic() +
  theme(
    legend.background = element_rect(
      fill = "grey90",
      size = 0.5, linetype = "solid"
    )
  )
#> Warning: The `size` argument of `element_rect()` is deprecated as of ggplot2 3.4.0.
#> ℹ Please use the `linewidth` argument instead.
#> This warning is displayed once every 8 hours.
#> Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
#> generated.
#> `geom_smooth()` using formula = 'y ~ x'

字符串


的数据

相关问题