Home > OS >  How to fill the background of a stat_poly_eq equation (ggpmisc) using ggplot2?
How to fill the background of a stat_poly_eq equation (ggpmisc) using ggplot2?

Time:10-09

Is there a way to fill the background of a stat_poly_eq equation ggpmisc with white color (or any other color) so that the black lines of the panel.grid are hidden?

# Data
df <- data.frame(x = c(1:100))
df$y <- 2   3 * df$x   rnorm(100, sd = 40)
df$yy <- 2   3 * df$x   0.1 * df$x^2   rnorm(100, sd = 40)

# Graph
library(ggplot2)
library(ggpmisc)

ggplot(data = df, aes(x = x, y = y))  
  scale_x_continuous(limits = c(0,100), expand = c(0,0))  
  scale_y_continuous(limits = c(0,400), expand = c(0,0))  
  theme(panel.grid.major=element_line(colour="black",size=0.1))  
  stat_poly_line()  
  stat_poly_eq(aes(
    label = paste(after_stat(eq.label),
                  after_stat(rr.label), sep = "*\", \"*")), size = 6, label.x = 0.07, label.y = 0.78)  
  geom_point()

Below is the graph as I would like:

enter image description here

Thanks for help

CodePudding user response:

This could be achieved by switching the default geom used by stat_poly_eq to add the label. By default ggpp::geom_text_npc is used but there is also a geom_label_npc:

library(ggplot2)
library(ggpmisc)

ggplot(data = df, aes(x = x, y = y))  
  scale_x_continuous(limits = c(0,100), expand = c(0,0))  
  scale_y_continuous(limits = c(0,400), expand = c(0,0))  
  theme(panel.grid.major=element_line(colour="black",size=0.1))  
  stat_poly_line()  
  stat_poly_eq(aes(
    label = paste(after_stat(eq.label),
                  after_stat(rr.label), sep = "*\", \"*")), 
    size = 6, label.x = 0.07, label.y = 0.78, 
    geom = "label_npc", label.size = 0)  
  geom_point()

enter image description here

  • Related