R 축을 기준으로 ggplot에 텍스트를 배치하는 방법

Sep 24 2020

ggplot에서 정의 된 제한이있는 막대 차트에 샘플 크기를 배치하기 위해 ggplot에서 geom_text ()를 사용하려고합니다. 대부분의 플롯에서 텍스트 배치에 대한 y- 값을 0으로 지정하는 것을 피할 수있었습니다. 그러나 일부 플롯의 경우 CI 막대가 0 미만으로 확장됩니다.

CI 막대에 샘플 크기가 인쇄되는 것을 방지하기 위해 x 축을 정의하는 플롯 여백과 관련하여 geom_text ()의 y 값을 지정하는 코드를 생성하려고합니다. 이 아이디어는 x 축에 상대적인 일반 코드를 생성하여 플롯에서 y의 최소값이 어디에 있든 상관없이이 코드를 모든 플롯에 적용 할 수 있습니다. 이상적으로는 가능한 경우이를 달성하기 위해 플롯 코드를 조정하고 싶습니다. 귀하의 의견에 미리 감사드립니다!

플롯 데이터베이스

data <- structure(list(Site_long = structure(c(2L, 2L, 1L, 1L), .Label = c("Hanauma Bay", 
"Waikiki"), class = "factor"), Shelter = structure(c(1L, 2L, 
1L, 2L), .Label = c("Low", "High"), class = c("ordered", "factor"
)), mean = c(0.096818329015544, 0.140368187765273, 0.364490168863912, 
0.452663275851282), sd = c(0.358269615215823, 0.442381836749624, 
0.431417057945072, 0.461599742148954), lower = c(-0.13725115292546, 
-0.148654612244481, 0.198658790631641, 0.337761753133984), upper = c(0.330887810956549, 
0.429390987775027, 0.530321547096184, 0.56756479856858), sample_size = c(9L, 
9L, 26L, 62L)), row.names = c(NA, -4L), groups = structure(list(
    Site_long = structure(1:2, .Label = c("Hanauma Bay", "Waikiki"
    ), class = "factor"), .rows = structure(list(3:4, 1:2), ptype = integer(0), class = c("vctrs_list_of", 
    "vctrs_vctr", "list"))), row.names = 1:2, class = c("tbl_df", 
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"))

플롯 코드

mult_compare_growth_all <- c("AB", "B", "A", "AB")

growth_plot <- ggplot(data = data, aes(fill=Shelter, y=mean, x=Site_long)) + 
  geom_bar(position = "dodge", stat="identity", width = .8) +
  scale_x_discrete(limits = position) +
  geom_errorbar(aes(ymin = lower, ymax = upper), position = position_dodge(.8), width = .1) +
  geom_text(aes(label = mult_compare_growth_all, y = data$upper), vjust = -.5, position = position_dodge(width = 0.8), size = 4) +
  scale_fill_grey(name = "Shelter", start = .8, end = .2) +
  labs(x = "Site", y = expression(paste("Coral growth (cm"^"2","/quarter)"))) +
  theme_classic(base_size = 14.5) +
  theme(text = element_text(size = 18), legend.position = "none", 
        axis.title.x = element_blank(),
        axis.text.y = element_text(angle = 90),
        axis.text.x = element_blank())

답변

1 rodolfoksveiga Sep 24 2020 at 05:14

y = -Inf텍스트 위치의 방향을 지정하는 데 사용할 수 있습니다 . 텍스트를 플롯 내부에 유지하려면 vjust요소를와 결합해야합니다 Inf. 그렇지 않으면 텍스트가 플롯에서 벗어납니다.

다음은 코드입니다.

ggplot(data = data, aes(fill=Shelter, y=mean, x=Site_long)) + 
  geom_bar(position = "dodge", stat = "identity", width = .8) +
  geom_errorbar(aes(ymin = lower, ymax = upper), position = position_dodge(.8), width = .1) +
  geom_text(aes(label = mult_compare_growth_all, y = data$upper), vjust = -.5,
            position = position_dodge(width = .8), size = 4) +
  geom_text(aes(label = sample_size, y = -Inf), vjust = -.3,
            position = position_dodge(width = .8)) +
  scale_fill_grey(name = "Shelter", start = .8, end = .2) +
  labs(x = "Site", y = expression(paste("Coral growth (cm"^"2","/quarter)"))) +
  theme_classic(base_size = 14.5) +
  theme(text = element_text(size = 18), legend.position = "none", 
        axis.title.x = element_blank(),
        axis.text.y = element_text(angle = 90),
        axis.text.x = element_blank())

그리고 출력 :

이것이 당신이 찾고있는 것인지 알려주세요.

1 Duck Sep 24 2020 at 05:14

제안으로 변수의 pf최소값을 기반으로 배치 계수 를 계산하고 다음 lower과 같은 조정 수량을 추가 할 수 있습니다.

library(ggplot2)
#Plot
mult_compare_growth_all <- c("AB", "B", "A", "AB")
#Factor for placement
pf <- min(data$lower)-0.02
#Code
ggplot(data = data, aes(fill=Shelter, y=mean, x=Site_long)) + 
  geom_bar(position = "dodge", stat="identity", width = .8) +
  geom_text(aes(y=pf,label=sample_size),position = position_dodge(0.8))+
  geom_errorbar(aes(ymin = lower, ymax = upper), position = position_dodge(.8), width = .1) +
  geom_text(aes(label = mult_compare_growth_all, y = upper),
            vjust = -.5, position = position_dodge(width = 0.8), size = 4)+
  scale_fill_grey(name = "Shelter", start = .8, end = .2) +
  labs(x = "Site", y = expression(paste("Coral growth (cm"^"2","/quarter)"))) +
  theme_classic(base_size = 14.5) +
  theme(text = element_text(size = 18), legend.position = "none",
        axis.title.x = element_blank(),
        axis.text.y = element_text(angle = 90),
        axis.text.x = element_blank())

산출:

brianavery Sep 24 2020 at 05:57

어떤 이유로 내가 이것을 플롯 할 때 내 것이 역전됩니다 (아마도 요인 순서).하지만 이것이 당신이 원하는 것이라고 생각합니까?

ggplot(data = data, aes(fill=Shelter, y=mean, x=Site_long)) + 
  geom_col(aes(fill=Shelter), position = "dodge", width = 0.8) + 
  geom_text(aes(y=lower, group=Shelter, label = sample_size), 
            position = position_dodge(width = 0.8), vjust=1.5) +
  geom_errorbar(aes(ymin = lower, ymax = upper), 
                position = position_dodge(.8), width = .1) +
  geom_text(aes(label = mult_compare_growth_all, y = data$upper), vjust = -.5, 
            position = position_dodge(width = 0.8), size = 4) +
  scale_fill_grey(name = "Shelter", start = .8, end = .2) +
  labs(x = "Site", y = expression(paste("Coral growth (cm"^"2","/quarter)"))) +
  theme_classic(base_size = 14.5) +
  theme(text = element_text(size = 18), legend.position = "none", 
        axis.title.x = element_blank(),
        axis.text.y = element_text(angle = 90),
        axis.text.x = element_blank())

결과 :

이것을 조금 분석해 보겠습니다.

geom_col()단일 값으로 지정된 높이로 이러한 종류의 막대 그림을 위해 만들어 졌기 때문에 사용 했습니다. geom_bar()당신이 한 방식으로 도 할 수 있습니다 .

그런 다음 올바른 막대에 레이블을 붙이기 geom_text()위해 group미학 이 필요하고 오류 막대의 맨 아래 에y=lower 레이블을 정확히 (성가 시게) 넣지 만 아래로 이동시키는 것을 지정해야합니다. 값 ( )은 아마도 어떤 의미가 있을지 모르지만 그것이 무엇인지 모르고 그 부분이 자동이되지 않도록 그것을 조작해야했습니다.vjust1.5