1

这是我的 df :

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

我创建了一个包含我的标签的列:

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

然后我做我的情节:

  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)

但是我在每个方面的文字都有问题:我想要 3 行(每个 sps 一行)。

我尝试使用符号“\n”,但未能尝试获得: 每年的“nb a = 1 \n nb b = 2 \n nb c = 3”

感谢帮助

4

2 回答 2

4

您必须将您想要分成几行的内容连接成一个字符串。

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))
于 2017-03-28T08:22:58.917 回答
2

您可以通过为标签创建单独的标签来实现您想要的data.frame


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))

于 2017-03-28T08:18:42.567 回答