0

In the following graph, how can I include the line of, for example group "B" in every facet, in black?

x <- c(seq(1, 10, 1), seq(1, 10, 1), seq(1, 10, 1))
c <- c(rep("A", 10), rep("B", 10), rep("C", 10))
y <- rnorm(30, 0, 1)
d <- data.frame(x = x, c = c, y = y)
d$c <- as.factor(d$c)

library(ggplot2)

ggplot() +
  geom_line(data = d, aes(x = x, y = y, color = c)) +
  facet_wrap(~c)

The following code, although suggested by this solution, only creates the line in category B in black but does not include it in all facets:

ggplot() +
  geom_line(data = d, aes(x = x, y = y, color = c)) +
  facet_wrap(~c)+
  geom_line(data=d[d$c=="B",], aes(x=x,y=y))

Thanks in advance.

Hendrik
  • 321
  • 1
  • 14
  • 1
    It's good to avoid using a function name, particularly a frequent one like `c`, for a custom object, particularly one hanging around in your workspace. Aside: `gl` is a convenient function to generate a factor with equal-sized (count) levels and custom labels. In your case: `my_color = gl(3, 10, labels = LETTERS[1:3])`. – I_O Aug 11 '23 at 14:57

1 Answers1

3

We can make a layer omitting the faceting variable to make it appear in every facet:

library(dplyr)
d |>
  ggplot(aes(x, y, color = c)) +
  geom_line(data = d |> filter(c == "B") |> select(-c), color = "gray") +
  geom_line() +
  facet_wrap(~c)

enter image description here

Jon Spring
  • 55,165
  • 4
  • 35
  • 53