如何在 ggplot2 facet_grid 中为 R 平方方程着色并将其移动到下一行?

How to colour and move R squared equation to next line in ggplot2 facet_grid?

对于我需要的图形维度,我希望 R 平方出现在下一行。我也想让文字的颜色对应factorz

的颜色
x <- c(1:50)
y <- rnorm(50,4,1)
z <- rep(c("J","F","H","I","J","K","L","M","N","O"), each  = 5)
df <- data.frame(x,y,z)

my.formula = y ~ x
ggplot(aes(x = x, y = y, color = z), data = df) +
  geom_point() + 
  stat_summary(fun.data=mean_cl_boot, geom="errorbar", width=0.2, colour="black") + 
  stat_summary(fun = mean, color = "black", geom ="point", size = 3,show.legend = FALSE) + 
  geom_smooth(method="lm", formula = y ~ x ) + 
  stat_poly_eq(formula = my.formula, aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")),  parse = TRUE, size = 2.5, col = "black")+
  facet_grid(.~z, scales = "free") + theme_classic()

这是一个方法。

  • 要使颜色正确,请注释掉 color = "black"
  • 要使回归方程下方的 R 平方,请使用 atop,请参阅 ?plotmath

atop 的结果没有左对齐,但这里是。

ggplot(mapping = aes(x = x, y = y, color = z), data = df) +
  geom_point() + 
  stat_summary(fun.data=mean_cl_boot, geom="errorbar", width=0.2, colour="black") + 
  stat_summary(fun = mean, color = "black", geom ="point", size = 3,show.legend = FALSE) + 
  geom_smooth(method="lm", formula = y ~ x ) + 
  stat_poly_eq(
    formula = my.formula, 
    aes(label = paste("atop(", ..eq.label.., ",", ..rr.label.., ")")),
    label.y = 0.9,
    parse = TRUE, 
    size = 2.5
    #, col = "black"
  )+
  facet_grid(.~z, scales = "free") + 
  theme_classic()