how to display text on several lines with geom_tex

2019-06-01 03:02发布

问题:

This is my df :

df <- data.frame(annee = rep(c(2003,2004), times = 1, each = 3), sps = c("a", "b", "c"), nb = 1:3)

I create a column containing my labels :

df$labels <- paste("nb", df$sps, "=", df$nb)

Then I do my plot :

  ggplot(df, aes(nb)) + 
  geom_density(aes(fill = sps, colour = sps), alpha = 0.1) + 
  facet_wrap(~ annee) +
  geom_text(data=df, aes(x=8, y=2.5, label= labels), colour="black", inherit.aes=FALSE, parse=FALSE)

But I have a problem with my text in each facet : I would like to have 3 lines (one for each sps).

I tried with the symbol "\n" but I failed in trying to obtain : "nb a = 1 \n nb b = 2 \n nb c = 3" for each year

Thanks for help

回答1:

You will have to concatenate what you want broken into several lines into one single string.

newdf <- aggregate(labels ~ annee, data = df, FUN = paste, collapse = "\n")

ggplot(df, aes(nb)) + 
  geom_density(aes(fill = sps, colour = sps), alpha = 0.1) + 
  facet_wrap(~ annee) +
  geom_text(data = newdf, aes(x = 8, y = 2, label = labels), color = "black") +
  scale_x_continuous(limits = c(0, 11)) +
  scale_y_continuous(limits = c(0, 2.25))


回答2:

You can achieve what you want by creating a separate data.frame for your labels:


library(tidyverse)

df <- data.frame(annee = rep(c(2003,2004),
                             times = 1, each = 3),
                 sps = c("a", "b", "c"),
                 nb = 1:3)

# create labels in separate data.frame
label_df <- df %>% 
  mutate(labels = paste("nb", sps, "=", nb)) %>% 
  group_by(annee) %>% 
  summarise(labels = paste(labels, collapse = "\n")) %>% 
  mutate(x = 6.5,
         y = 2.2)


ggplot(df, aes(nb)) + 
  geom_density(aes(fill = sps, colour = sps), alpha = 0.1) + 
  facet_wrap(~annee) +
  geom_text(data = label_df, aes(x = x, y = y, label = labels)) +
  coord_cartesian(ylim = c(0, 2.4), xlim = c(1, 8))