[withR] 좀더 하는 ggplot2-Making a Stacked Bar Graph(누적 그래프 다루기)

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

#library(ggplot2)

#library(gcookbook) 예체 data set 포함

library(gcookbook)
ggplot(cabbage_exp, aes(x=Date, y=Weight, fill=Cultivar)) +
geom_bar(stat=”identity”)

dodge 그래프에서는 파란색, 빨간색 그래프를 옆으로 나란히 그려 놓지만 누적 그래프는 위로 쌓아서 올렸다.

dodge 그래프

이번에는 범례에서 C39와 c52의 순서를 바꾸도록 해보자

ggplot(cabbage_exp, aes(x=Date, y=Weight, fill=Cultivar)) +
geom_bar(stat=”identity”) +
guides(fill=guide_legend(reverse=TRUE))

guides(fill=guide_legend(reverse=TRUE))을 추가 해줌으로써 벌c39/c52에서 c52가 위 , c39가 밑에 오는것 을 볼 수 있다.

install.packages(“plyr”)

library(plyr) #desc()를 사용하기 위해서 필요하다.

ggplot(cabbage_exp, aes(x=Date, y=Weight, fill=Cultivar, order=desc(Cultivar))) +
geom_bar(stat=”identity”)

order=desc(Cultivar)를 주어수 순서를 정렬한다. 위에 맨처음 그림과 비교 하면 차이를 알수 있다.

ggplot(cabbage_exp, aes(x=Date, y=Weight, fill=Cultivar)) +
geom_bar(stat=”identity”, colour=”black”) +
guides(fill=guide_legend(reverse=TRUE)) +
scale_fill_brewer(palette=”Pastel1")

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