[withR]좀더 하는 ggplot2-Adding Labels to a Bar Graph(막대그래프에 라벨 추가하기)
#library(ggplot2)
#library(gcookbook)
geom_text()를 통해서 그래프 위에 라벨을 추가해 보자.
library(ggplot2)
library(gcookbook)
#그래프 맨위에 표시하기
ggplot(cabbage_exp, aes(x=interaction(Date, Cultivar), y=Weight)) +
geom_bar(stat=”identity”) +
geom_text(aes(label=Weight), vjust=1.5, colour=”white”)
#그래프 머리위에 표시하기
ggplot(cabbage_exp, aes(x=interaction(Date, Cultivar), y=Weight)) +
geom_bar(stat=”identity”) +
geom_text(aes(label=Weight), vjust=-0.2)


geoom_text()도 여러가지 옵션을 가지고 있다. aes(label=Weight)는 라벨 대상이 Weight임을 알려준다.
vjust=숫자, 라벨에 위치를 조정해준다. 양수를 가질수록 아래로 내려오고, 음수를 가질수록 그래프 위로 올라 간다.
또한 colour=”색”을 통해서 라벨에 색상을 변경할 수 있다.
#y축의 범위 조정
ggplot(cabbage_exp, aes(x=interaction(Date, Cultivar), y=Weight)) +
geom_bar(stat=”identity”) +
geom_text(aes(label=Weight), vjust=-0.2) +
ylim(0, max(cabbage_exp$Weight) * 1.05)
#y변수 값을 이용한 라벨 위치 조정
ggplot(cabbage_exp, aes(x=interaction(Date, Cultivar), y=Weight)) +
geom_bar(stat=”identity”) +
geom_text(aes(y=Weight+0.1, label=Weight))
#dodge그래프
ggplot(cabbage_exp, aes(x=Date, y=Weight, fill=Cultivar)) +
geom_bar(stat=”identity”, position=”dodge”) +
geom_text(aes(label=Weight), vjust=1.5, colour=”white”,
position=position_dodge(.9), size=3)

다음은 누적 그래프 위에 라벨 표시를 해보자.
이 작업은 먼저 데이터를 약간 변경 시켜야 한다.
library(plyr)
ce <- arrange(cabbage_exp, Date, Cultivar)
arrange()는 정렬 함수 이다.
ce <- ddply(ce, “Date”, transform, label_y=cumsum(Weight))
ce

ggplot(ce, aes(x=Date, y=Weight, fill=Cultivar)) +
geom_bar(stat=”identity”) +
geom_text(aes(y=label_y, label=Weight), vjust=1.5, colour=”white”)

라벨이 기본적인 위치가 Weight변수의 크기로 결정 되기 때문에 Date별로 누적된 Weight값을 가진 label_y변수를
새롭게 생성하여 라벨의 높이를 지정한다. 그리고 vjust=”숫자”로 미세 조정을 하게 된다.
lable_y값을 조절하면 라벨이 그래프 중간에 위치하게 만들 수 있다.
ce <- ddply(ce, “Date”, transform, label_y=cumsum(Weight)-0.5*Weight)
ggplot(ce, aes(x=Date, y=Weight, fill=Cultivar)) +
geom_bar(stat=”identity”) +
geom_text(aes(y=label_y, label=Weight), colour=”white”)

라벨에 format을 이용해서 “kg”을 추가 가능하다.
ggplot(ce, aes(x=Date, y=Weight, fill=Cultivar)) +
geom_bar(stat=”identity”, colour=”black”) +
geom_text(aes(y=label_y, label=paste(format(Weight, nsmall=2), “kg”)),size=4) +
guides(fill=guide_legend(reverse=TRUE)) +
scale_fill_brewer(palette=”Pastel1")


