0

consider the following tibble

library(tidyverse)
df <-tibble(year = rep(1981:2020,4),
       x = rep(letters[1:8],20),
       y = rnorm(n = 160,0,1),
       group = rep(letters[10:13],40))

I want to plot a faceted grid based on variable group and as text in each panel, the years (year) corresponding to each group (group).

Below a failed attempt where years are overlapping and not correct

ggplot() +
  geom_line(data = df, aes(x = x, y = y, color = group)) +
  geom_text(
    data = df,
    aes(
      x = x,
      y = 3,
      label = year,
      color = group
    ),
    alpha = 0.7,
    show.legend = FALSE
  ) +
  facet_grid( ~ group)

Thanks for support!

1 Answer 1

1

I'm not sure I understand what you want, but you can try the following

ggplot() +
  geom_line(data = df, aes(x = x, y = y, color = group)) +
  geom_text(
    data = df,
    aes(
      x = x,
      y = 3,
      label = year,
      color = group
    ),
    alpha = 0.7,
    show.legend = FALSE,
    position = position_stack(vjust = 1.5), 
#    stat = "unique"
  ) +
  facet_grid( ~ group)

If you don't want the year to be repeated, uncomment the stat = "unique" line.

UPDATE
If you want a horizontal alignment you can create a new data frame

df2 <- df %>% 
  group_by(x, group) %>% 
  summarise(year = str_c(unique(year), collapse=", "))

ggplot() +
  geom_line(data = df, aes(x = x, y = y, color = group)) +
  geom_text(
    data = df2,
    aes(
      x = x,
      y = 1,
      label = year,
      color = group
    ),
    alpha = 0.7,
    show.legend = FALSE,
    position = position_stack(vjust = 1.5), 
    stat = "unique"
  ) +
  facet_grid( ~ group)

but with this alignment labels will overlap. You can try reducing the font-size or using facet_wrap to arrange the panels on two rows.

You can also manipulate strings in df2 and add "\n" where you need it, but I think this cannot be easily adapted to every string.

Sign up to request clarification or add additional context in comments.

3 Comments

geom_text(data = df, aes(x = 1,y = 3,label = year, color = group), alpha = 0.7, show.legend = FALSE, position = position_stack(vjust = 1.5), stat = "unique") + The following is one step in the right direction. Nevertheless, the years are still stacking vertically whereas I want them to be aligned horizontally... can you help with the last mile? thanks!
I updated my answer. I hope I understand your question correctly
Thanks that works. To avoid overlap, I just set x =5

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.