programing

ggplot2를 사용하여 R의 각 막대에 대해 gem_bar 위에 레이블을 붙이는 방법

javamemo 2023. 6. 19. 21:05
반응형

ggplot2를 사용하여 R의 각 막대에 대해 gem_bar 위에 레이블을 붙이는 방법

ggplot2를 사용하여 R의 gem_bar 위에 레이블을 배치하는 방법을 찾았지만 하나의 막대에만 레이블(숫자)을 배치했습니다.

예를 들어, 각 x축에 대해 두 개의 막대가 있습니다. 같은 작업을 수행하는 방법은 무엇입니까?

내 데이터와 코드는 다음과 같습니다.

dat <- read.table(text = "sample Types Number
sample1 A   3641
sample2 A   3119
sample1 B   15815
sample2 B   12334
sample1 C   2706
sample2 C   3147", header=TRUE)

library(ggplot2)
bar <- ggplot(data=dat, aes(x=Types, y=Number, fill=sample)) + 
  geom_bar(position = 'dodge') + geom_text(aes(label=Number))

그러면 다음과 같은 이점을 얻을 수 있습니다.enter image description here

숫자 텍스트도 "회피" 패턴으로 배치된 것 같습니다.gem_text manual에서 정보를 찾았지만 작동하지 않습니다.

제안?

사용해 보십시오.

ggplot(data=dat, aes(x=Types, y=Number, fill=sample)) + 
     geom_bar(position = 'dodge', stat='identity') +
     geom_text(aes(label=Number), position=position_dodge(width=0.9), vjust=-0.25)

ggplot output

x가 POSIX.ct 날짜일 때 gem_bar()와 함께 position_dodge()를 사용하려면 너비에 86400을 곱해야 합니다.

ggplot(data=dat, aes(x=Types, y=Number, fill=sample)) + 
 geom_bar(position = "dodge", stat = 'identity') +
 geom_text(aes(label=Number), position=position_dodge(width=0.9*86400), vjust=-0.25)

언급URL : https://stackoverflow.com/questions/12018499/how-to-put-labels-over-geom-bar-for-each-bar-in-r-with-ggplot2

반응형