[英]Annotate outside plot area once in ggplot with facets
我想在一個刻面的ggplot中在繪圖區域外添加一個注釋。 我可以獲得我想要的注釋,但是每個方面都重復了這個注釋。 如何讓這個注釋只出現一次?
例如,要在左上角注釋“XX”,我可以使用:
library("ggplot2")
ggplot(mtcars, aes(x = hp, y = mpg)) +
geom_point() +
facet_grid(.~cyl ) +
annotate("text", x = -20, y = 36, label = "XX") +
coord_cartesian(xlim = c(50, 350), ylim = c(10, 35), clip = "off")
然而,這實際上將其注釋到每個方面的左上角。
如何讓它只顯示一次?
您可以使用labs()
tag
在圖表上放置單個標記標簽。
ggplot(mtcars, aes(x = hp, y = mpg)) +
geom_point() +
facet_grid(.~cyl ) +
labs(tag = "XX") +
coord_cartesian(xlim = c(50, 350), ylim = c(10, 35), clip = "off")
但是,默認為“左上角”,這可能不是您想要的。 您可以使用主題元素plot.tag.position
來移動它,或者作為坐標(0到1之間在繪圖空間中)或者像"topright"
這樣的字符串。
ggplot(mtcars, aes(x = hp, y = mpg)) +
geom_point() +
facet_grid(.~cyl ) +
labs(tag = "XX") +
coord_cartesian(xlim = c(50, 350), ylim = c(10, 35), clip = "off") +
theme(plot.tag.position = c(.01, .95))
或者,包cowplot
具有方便的注釋函數draw_label()
。 當與ggdraw()
結合使用時,可以在畫布/工作表上的任何位置注釋,坐標范圍從0到1(相對於整個畫布)。 函數cowplot::draw_label()
在引擎蓋下使用ggplot2::annotation_custom()
。
library(ggplot2)
library(cowplot)
#> Warning: package 'cowplot' was built under R version 3.5.2
#>
#> Attaching package: 'cowplot'
#> The following object is masked from 'package:ggplot2':
#>
#> ggsave
# Revert to default theme; see https://stackoverflow.com/a/41096936/5193830
theme_set(theme_grey())
p <- ggplot(mtcars, aes(x = hp, y = mpg)) +
geom_point() +
facet_grid(. ~ cyl)
ggdraw(p) + draw_label("XX", x = 0.02, y = 0.97)
由reprex包創建於2019-01-14(v0.2.1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.