【发布时间】:2020-12-10 23:59:20
【问题描述】:
我确实花了几天时间寻找这个问题的正确答案。我想在绘图区域的外部(图例上方或下方)放置额外的文本/注释,在具有如下嵌套构面的 geom_bar 上。
我尝试过的一些事情: annotate_custom 和 annotate 不起作用,因为它们在每个单独的方面都添加了注释。 Grid.text 工作(我能够正确放置文本),但我无法使用 ggsave(这很重要)来保存完成的绘图。
我还查看了有关在多面图的单个面上创建注释的答案。这些答案没有帮助,因为我希望文本/注释位于绘图区域之外(图例上方/下方)而不是绘图区域本身。
提前感谢您的帮助!
以下是一些数据:
library(ggplot2)
library(ggh4x) # for the facet_nested function
my.df<-data.frame("top.nest"=sample(c("Group.1","Group.2","Group.3"),26,rep=T),
"bottom.nest"=sample(c("Cat.1","Cat.2","Cat.3","Cat.4","Cat.5"),26,rep=T),
"my.teams"=c(LETTERS),
"quantity"=abs(round(rnorm(26,200,20))),
"my.factor"=sample(c("A","B","C"),26,rep=T))
my.plot<- ggplot(my.df, aes(my.teams, quantity, fill = my.factor)) +
geom_bar(stat = "identity") +
geom_col(width=1) +
scale_fill_manual(values=c("blue","red","green"), labels = c("A","B","C")) +
labs(title = "How do you add text/annotation either below or above the legend",
subtitle="of a facet barplot in ggplot?") +
theme(plot.title = element_text(hjust = 0.5, size=12),
plot.subtitle = element_text(hjust=0.5, size=12)) +
scale_y_continuous(expand = c(0, 0), limits=c(0,250)) +
facet_nested(~top.nest + bottom.nest, scales="free_x", space="free")
我尝试了以下建议,但对我不起作用。我将这三行添加到原始代码中。
labs(tag = "XX") +
coord_cartesian(xlim = c(50, 350), ylim = c(10, 35), clip = "off") +
theme(plot.tag.position = c(.01, .95))
无论我在 facet_nested 命令之前还是之后添加它,结果都是一样的(见下图)。我的预感是,在这个问题的第一个回复中提供的示例中,x 变量是数字的。我的不是。
编辑:好的,代码现在可以使用添加的 3 行,只要我删除 xlim=c() 部分。它适用于 ylim=c(),或者只是删除所有限制。考虑到 x 变量不是(正如我之前提到的)数字,这有点道理。
这是完整的代码,以及成功的情节!
my.plot<- ggplot(my.df, aes(my.teams, quantity, fill = my.factor)) +
geom_bar(stat = "identity") +
geom_col(width=1) +
scale_fill_manual(values=c("blue","red","green"), labels = c("A","B","C")) +
labs(title = "Successfully added text/annotation below the legend",
subtitle="of a facet barplot in ggplot") +
theme(plot.title = element_text(hjust = 0.5, size=12),
plot.subtitle = element_text(hjust=0.5, size=12)) +
scale_y_continuous(expand = c(0, 0), limits=c(0,250)) +
facet_nested(~top.nest + bottom.nest, scales="free_x", space="free") +
labs(tag = "XX") +
coord_cartesian(clip = "off") +
theme(plot.tag.position = c(.95, .6))
【问题讨论】:
-
你看到这个问题了吗? stackoverflow.com/questions/53167616/…
-
是的。它对我不起作用。我的直觉是,这是因为我的 x 变量不是数字的(它是一个字符变量——因子的工作方式相同)。我认为 clip="off" 会破坏条形,就像我在上面添加的图像中一样。
-
好的,它现在对我有用。但我不得不放弃限制。请参阅上面的编辑。谢谢你的帮助!!
-
好的,谢谢。我会的。
-
所以,我可以使用 MrFlick 链接到的响应,并对其进行一些调整。我假设因为我的 x 变量不是数字,所以包含 xlim 是在上面第二张图片中造成问题的原因。这是完整的代码(带有额外的文本行)和结果:哦,我还展示了如何添加多行文本,并左对齐文本。