programing

개별 면에 텍스트 주석 달기 ggplot2

css3 2023. 6. 24. 09:27

개별 면에 텍스트 주석 달기 ggplot2

다음 코드를 사용하여 플롯의 마지막 면에 일부 텍스트에 주석을 달려고 합니다.

library(ggplot2)
p <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
p <- p + facet_grid(. ~ cyl)
p <- p + annotate("text", label = "Test", size = 4, x = 15, y = 5)
print(p)

enter image description here

하지만 이 코드는 모든 면에 텍스트에 주석을 달았습니다.주석이 달린 텍스트를 한 면에서만 얻으려면 어떻게 해야 합니까?

기.annotate()면이 있는 그림의 모든 패널에 동일한 레이블을 추가합니다.각 패널에 다른 주석을 추가하거나 일부 패널에만 주석을 추가하려면 다음 대신 지오메트리를 사용해야 합니다.annotate()기하학적하려면 다음과 .geom_text()우리는 다른 미학에 매핑될 변수와 페이싱에 사용되는 변수를 위해 하나의 열과 열에 레이블의 텍스트가 포함된 데이터 프레임을 조립해야 합니다.

일반적으로 다음과 같은 작업을 수행합니다.

ann_text <- data.frame(mpg = 15,wt = 5,lab = "Text",
                       cyl = factor(8,levels = c("4","6","8")))
p + geom_text(data = ann_text,label = "Text")

요인 변수를 완전히 지정하지 않고 작동해야 하지만 다음과 같은 경고가 발생할 수 있습니다.

enter image description here

기.annotate()면이 있는 그림의 모든 패널에 동일한 레이블을 추가합니다.각 패널에 다른 주석을 추가하거나 일부 패널에만 주석을 추가하려면 다음 대신 지오메트리를 사용해야 합니다.annotate()기하학적하려면 다음과 .geom_text()우리는 다른 미학에 매핑될 변수와 페이싱에 사용되는 변수를 위해 하나의 열과 열에 레이블의 텍스트가 포함된 데이터 프레임을 조립해야 합니다.이 대답은 두 가지 모두에 대한 예시입니다.facet_wrap()그리고.facet_grid().

텍스트 주석이 없는 그림은 다음과 같습니다.

library(ggplot2)

p <- ggplot(mtcars, aes(mpg, wt)) +
  geom_point() +
  facet_grid(. ~ cyl) +
  theme(panel.spacing = unit(1, "lines"))
p

plot without text annotations

텍스트 주석을 보관할 추가 데이터 프레임을 생성합니다.

dat_text <- data.frame(
  label = c("4 cylinders", "6 cylinders", "8 cylinders"),
  cyl   = c(4, 6, 8)
)
p + geom_text(
  data    = dat_text,
  mapping = aes(x = -Inf, y = -Inf, label = label),
  hjust   = -0.1,
  vjust   = -1
)

plot with text annotations at edges

또는 각 레이블의 위치를 수동으로 지정할 수 있습니다.

dat_text <- data.frame(
  label = c("4 cylinders", "6 cylinders", "8 cylinders"),
  cyl   = c(4, 6, 8),
  x     = c(20, 27.5, 25),
  y     = c(4, 4, 4.5)
)

p + geom_text(
  data    = dat_text,
  mapping = aes(x = x, y = y, label = label)
)

plot with manually positioned text labels

두 가지 면에 걸쳐 그림에 레이블을 지정할 수도 있습니다.

dat_text <- data.frame(
  cyl   = c(4, 6, 8, 4, 6, 8),
  am    = c(0, 0, 0, 1, 1, 1)
)
dat_text$label <- sprintf(
  "%s, %s cylinders",
  ifelse(dat_text$am == 0, "automatic", "manual"),
  dat_text$cyl
)
p +
  facet_grid(am ~ cyl) +
  geom_text(
    size    = 5,
    data    = dat_text,
    mapping = aes(x = Inf, y = Inf, label = label),
    hjust   = 1.05,
    vjust   = 1.5
  )

facet by two variables

주의:

  • 사용할 수 있습니다.-Inf그리고.Inf패널 가장자리에 텍스트를 배치합니다.
  • 사용할 수 있습니다.hjust그리고.vjust텍스트 맞춤을 조정합니다.
  • 프레임 텍스레데이터프레임블이트▁the프임▁label레▁data.dat_text는 용자와함작열있합니어다야이는동사하께▁that▁your▁column와 함께 사용할 수 열이 합니다.facet_grid()또는facet_wrap().

보고서나 출판물에 대해 표면에 레이블을 쉽게 지정하는 방법을 찾고 있는 사람이 있다면 (CRAN) 패키지는 매우 정교합니다.tag_facet()&tag_facet_outside()기능들.

library(ggplot2)

p <- ggplot(mtcars, aes(qsec, mpg)) + 
  geom_point() + 
  facet_grid(. ~ am) +
  theme_bw(base_size = 12)

# install.packages('egg', dependencies = TRUE)
library(egg)

내부 태그

체납

tag_facet(p)

참고: 스트립 텍스트와 배경을 유지하려면 추가한 후 다시 입력하십시오.theme 는또제를 제거합니다.theme(strip.text = element_blank(), strip.background = element_blank())에서.tag_facet()기능.

tag_facet <- function(p, open = "(", close = ")", tag_pool = letters, x = -Inf, y = Inf, 
                      hjust = -0.5, vjust = 1.5, fontface = 2, family = "", ...) {

  gb <- ggplot_build(p)
  lay <- gb$layout$layout
  tags <- cbind(lay, label = paste0(open, tag_pool[lay$PANEL], close), x = x, y = y)
  p + geom_text(data = tags, aes_string(x = "x", y = "y", label = "label"), ..., hjust = hjust, 
                vjust = vjust, fontface = fontface, family = family, inherit.aes = FALSE) 
}

오른쪽 위 정렬 및 로마 숫자 사용

tag_facet(p, x = Inf, y = Inf, 
          hjust = 1.5,
          tag_pool = as.roman(1:nlevels(factor(mtcars$am))))

왼쪽 아래 정렬 및 대문자 사용

tag_facet(p, 
          x = -Inf, y = -Inf, 
          vjust = -1,
          open = "", close = ")",
          tag_pool = LETTERS)

고유한 태그 정의

my_tag <- c("i) 4 cylinders", "ii) 6 cyls")
tag_facet(p, 
          x = -Inf, y = -Inf, 
          vjust = -1, hjust = -0.25,
          open = "", close = "",
          fontface = 4,
          size = 5,
          family = "serif",
          tag_pool = my_tag)

태그 아웃사이드

p2 <- ggplot(mtcars, aes(qsec, mpg)) + 
  geom_point() + 
  facet_grid(cyl ~ am, switch = 'y') +
  theme_bw(base_size = 12) +
  theme(strip.placement = 'outside')

tag_facet_outside(p2)

편집: 스티커 레이블러 패키지를 사용하여 다른 대안 추가

- `.n` numbers the facets numerically: `"1"`, `"2"`, `"3"`...
- `.l` numbers the facets using lowercase letters: `"a"`, `"b"`, `"c"`...
- `.L` numbers the facets using uppercase letters: `"A"`, `"B"`, `"C"`...
- `.r` numbers the facets using lowercase Roman numerals: `"i"`, `"ii"`, `"iii"`...
- `.R` numbers the facets using uppercase Roman numerals: `"I"`, `"II"`, `"III"`...

# devtools::install_github("rensa/stickylabeller")
library(stickylabeller)

ggplot(mtcars, aes(qsec, mpg)) + 
  geom_point() + 
  facet_wrap(. ~ am, 
             labeller = label_glue('({.l}) am = {am}')) +
  theme_bw(base_size = 12)

reprex 패키지(v0.2.1)에 의해 생성됨

위의 연구소="라고 생각합니다""텍스트"는 쓸모가 없으며, 아래 코드도 괜찮습니다.

ann_text <- data.frame(mpg = 15,wt = 5,
                       cyl = factor(8,levels = c("4","6","8")))
p + geom_text(data = ann_text,label = "Text" )

그러나 다른 하위 그래프에서 레이블을 다르게 지정하려는 경우 다음과 같은 방법으로 괜찮습니다.

ann_text <- data.frame(mpg = c(14,15),wt = c(4,5),lab=c("text1","text2"),
                       cyl = factor(c(6,8),levels = c("4","6","8")))
p + geom_text(data = ann_text,aes(label =lab) )

레이블 데이터 프레임의 작동 방식을 명확히 하기 위해 조란의 훌륭한 답변에 대해 약간 확장합니다.

"mpg"와 "wt"를 각각 x와 y 좌표로 생각할 수 있습니다(Kamil의 훌륭한 답변에서처럼 원래 변수 이름을 바꾸는 것보다 추적하는 것이 더 쉽다는 것을 알게 되었습니다).레이블당 하나의 행이 필요하며 "원형" 열에는 각 행이 연관된 면이 표시됩니다.

ann_text<-data.frame(mpg=c(25,15),wt=c(3,5),cyl=c(6,8),label=c("Label 1","Label 2"))

ann_text
>  mpg wt cyl  label
>  25  3   6   Label 1
>  15  5   8   Label 2

p <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
p <- p + facet_grid(. ~ factor(cyl))
p + geom_text(data = ann_text,label=ann_text$label)

plot with labels

저는 그것에 대해 몰랐습니다.egg패키지, 그래서 여기 평원이 있습니다.ggplot2패키지 솔루션

library(tidyverse)
library(magrittr)
Data1=data.frame(A=runif(20, min = 0, max = 100), B=runif(20, min = 0, max = 250), C=runif(20, min = 0, max = 300))
Data2=data.frame(A=runif(20, min = -10, max = 50), B=runif(20, min = -5, max = 150), C=runif(20, min = 5, max = 200))
bind_cols(
Data1 %>% gather("Vars","Data_1"),
Data2 %>% gather("Vars","Data_2")
) %>% select(-Vars1) -> Data_combined
Data_combined %>%
  group_by(Vars) %>%
  summarise(r=cor(Data_1,Data_2),
            r2=r^2,
            p=(pt(abs(r),nrow(.)-2)-pt(-abs(r),nrow(.)-2))) %>%
  mutate(rlabel=paste("r:",format(r,digits=3)),
         plabel=paste("p:",format(p,digits=3))) ->
  label_df 
label_df %<>% mutate(x=60,y=190)
Data_combined %>%
  ggplot(aes(x=Data_1,y=Data_2,color=Vars)) +
  geom_point() + 
  geom_smooth(method="lm",se=FALSE) +
  geom_text(data=label_df,aes(x=x,y=y,label=rlabel),inherit.aes = FALSE) + 
  geom_text(data=label_df,aes(x=x,y=y-10,label=plabel),inherit.aes = FALSE) + 
    facet_wrap(~ Vars)

언급URL : https://stackoverflow.com/questions/11889625/annotating-text-on-individual-facet-in-ggplot2