如何在多面包装中使用geom_text在多行上显示文本 [英] how to display text on several lines with geom_text in faceting wrap

查看:81
本文介绍了如何在多面包装中使用geom_text在多行上显示文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的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"

感谢帮助

解决方案

您将必须将要分成几行的内容连接到一个字符串中.

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

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

解决方案

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

这篇关于如何在多面包装中使用geom_text在多行上显示文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆