Home > Blockchain >  How to add variables in a column as text using ggplot, facet_grid and geom_text
How to add variables in a column as text using ggplot, facet_grid and geom_text

Time:05-05

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!

CodePudding user response:

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.

  • Related