ggforce annotation without the geom?

Viewed 129

I want to create a ggforce annotation (via the geom_mark_* functions) but I don't want the shape of the geom visible. I've tried setting various alpha levels to zero but to no avail. In other words, I want to preserve the annotation line and label but not the circle circling the point in the reprex below. How can I conceal it?

Edit: in response to one possible solution below, I can't use the color argument because I have more than one background color.

library(tidyverse)
#> Warning: package 'ggplot2' was built under R version 4.0.5
#> Warning: package 'dplyr' was built under R version 4.0.5
library(ggforce)
#> Warning: package 'ggforce' was built under R version 4.0.4

df2 <- tibble(
  x = 1:10,
  y = rnorm(10),
  z = LETTERS[1:10]
)

ggplot(df2, aes(x, y)) +
  geom_point() +
  geom_mark_circle(
    aes(label = z, filter = x == 5)
  ) +
  annotate(
    "rect",
    xmin = 0, 
    xmax = 5,
    ymin = -Inf,
    ymax = Inf,
    fill = "steelblue",
    alpha = 0.3
  ) +
  annotate(
    "rect",
    xmin = 5, 
    xmax = Inf,
    ymin = -Inf,
    ymax = Inf,
    fill = "firebrick",
    alpha = 0.3
  )

Created on 2021-09-02 by the reprex package (v1.0.0)

2 Answers

One trick I have used for my work is to set background the same color as mark:

ggplot(df2, aes(x, y)) +
  geom_point() +
  geom_mark_circle(
    aes(label = z, filter = x == 5), color = "grey90"
  ) + 
  theme(panel.background = element_rect("grey90"))

enter image description here

Edit

ggplot(df2, aes(x, y)) +
  geom_point() +
  geom_mark_circle(
    aes(label = z, filter = x == 5), expand = unit(0, "mm")
  ) +
  annotate(
    "rect",
    xmin = 0, 
    xmax = 5,
    ymin = -Inf,
    ymax = Inf,
    fill = "steelblue",
    alpha = 0.3
  ) +
  annotate(
    "rect",
    xmin = 5, 
    xmax = Inf,
    ymin = -Inf,
    ymax = Inf,
    fill = "firebrick",
    alpha = 0.3
  )

enter image description here

An alternative that should work for one as well as multiple points is to simply set linetype = 0, to skip drawing the shape of the geom.

library(tidyverse)
library(ggforce)

df2 <- tibble(
  x = 1:10,
  y = rnorm(10),
  z = LETTERS[1:10]
)

p <- 
  ggplot(df2, aes(x, y)) +
  annotate(
    "rect",
    xmin = c(0, 5), xmax = c(5, Inf),
    ymin = c(-Inf, -Inf), ymax = c(Inf, Inf),
    fill = c("steelblue", "firebrick"),
    alpha = 0.3
  ) +
  geom_point()

For a single point:

p +
  geom_mark_circle(
    aes(label = z, filter = x == 5),
    linetype = 0
  )

For multiple points:

p +
  geom_mark_circle(
    aes(label = z, filter = x < 7.5 & x > 2.5),
    linetype = 0
  )

Created on 2021-09-03 by the reprex package (v1.0.0)

Related