[withR]좀더 하는 ggplot2 — Proportional Stacked Bar Graph(비율 누적 그래프)

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

#library(ggplot2)

#library(plyr)

#library(gcookbook) 라이브러리 설치

비율 누적 막대그래프 그리는 방법에 대해서 알아보자.

앞에서 누적 그래프를 다루었다.

이번엔 여기서 좀 변형되어 y변수를 100%비율로 두는 그래프를 그려보고자 한다.

library(plyr)을 통해서 비율변수를 새롭게 추가해 보겠다.

library(ggplot2)

library(plyr)

library(gcookbook) #예제 파일 포함

ce <- ddply(cabbage_exp, “Date”, transform, percent_weight=Weight/sum(Weight)*100)

여기서 하나 ddply 는 그룹별 연산을 하고 그것을 다시 데이터프레임 형식으로 만들어주는 데이터를 다루는 함수이다.

위 코드에서는 cabbage_exp데이터 셋을 Date별로, percent_weight을 계산하는 의미이다. transform옵션을 넣어야 변수명을 바꾸거나

새로운 변수를 추가 할 수 있다.

ggplot(ce, aes(x=Date, y=percent_weight, fill=Cultivar))+geom_bar(stat=”identity”)

새롭게 만든 percent_weight변수로 100%비율 누적그래프를 생성했다.

ddply를 통해서 데이터를 바꾸는 작업을 하는게 어렵다고 생각한다면 더 쉽게 하는 옵션이 있다.

ggplot에서 ddply이 작업을 알아서 해준다.

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

geom_bar()안에 position=”fill” 옵션을 넣어주면 위에서 처럼 데이터 작업을 하지 않아도 0과 1사이의 비율을 가지는

비율 누적 그래프가 그려 진다.

파스텔톤의 생삭을 원한다면 아래 코드 처럼 해보자.

ggplot(ce, aes(x=Date, y=Weight, fill=Cultivar))+
geom_bar(stat=”identity”, colour=”black”,position=”fill”)+
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