簡體   English   中英

使用facet在ggplot中注釋一次外部繪圖區域

[英]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")

注釋情節

然而,這實際上將其注釋到每個方面的左上角。

如何讓它只顯示一次?

它實際上非常簡單,只需要一個標簽矢量 ,其中你不想繪制的是空字符串""

library("ggplot2")

ggplot(mtcars, aes(x = hp, y = mpg)) +
  geom_point() +
  annotate("text", x = -20, y = 36, label = c("XX", "", "")) +
  facet_grid(.~cyl ) + 
  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))

在此輸入圖像描述

使用geom_text

dummy <- data.frame(cyl = c(4), l = c("XX"), stringsAsFactors = F)

ggplot(mtcars, aes(x = hp, y = mpg)) +
  geom_point() +
  geom_text(data=dummy, aes(label=l), x = -20, y = 36) +
  facet_grid(.~cyl ) + 
  coord_cartesian(xlim = c(50, 350), ylim = c(10, 35), clip = "off")

在此輸入圖像描述

或者,包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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM