[withR]좀더 하는 ggplot2-Adding Labels to a Bar Graph(막대그래프에 라벨 추가하기)

GC Jeong
GC Jeong
Sep 7, 2018 · 2 min read

#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")

신나는연구소

신나는 일을 하며 삽시다!

GC Jeong

Written by

GC Jeong

#Data Analyst #세상을 보는 데이터 분석가 #책을 읽는 몽상가

신나는연구소

신나는 일을 하며 삽시다!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade