2

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

stefan
  • 90,330
  • 6
  • 25
  • 51
denis
  • 199
  • 1
  • 8
  • The idea is not to remove the panel.grid, but rather that they do not intersect the equation (in other words, that the equation and its white background are positioned in the foreground to hide this panel.grid) – denis Oct 08 '22 at 08:05
  • A function/argument to control the background of a stat_poly_eq equation (color, size...) would be aesthetically very useful in some contexts – denis Oct 08 '22 at 08:11

1 Answers1

2

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

stefan
  • 90,330
  • 6
  • 25
  • 51
  • great! thank you. We can add some other arguments to 'geom = "label_npc", label.size = 0' like alpha=0.5, colour = "red", fill = "pink"...However, do you think it is possible to control the size of the background, in height or in width? – denis Oct 08 '22 at 09:29
  • It can be done using 'label.padding = grid::unit(0.5, "cm")' which is the amount of padding around label (defaults to 0.25 lines). Also possible to add 'label.r = grid::unit(0.5, "cm")' to control the radius of rounded corners (defaults to 0.15 lines). Thanks again. – denis Oct 08 '22 at 09:41
  • An explanation: the reason why I decided to have "text_npc" as default is that a label, unless one is careful about its location, can accidentaly oclude observations. – Pedro J. Aphalo Oct 17 '22 at 08:05