Ggplot2를 사용하여 r에서 gantt 차트를 만드는 방법
간트 차트(Gantt Chart)는 다양한 이벤트의 시작 시간과 종료 시간을 나타내는 차트 유형입니다.
이 튜토리얼에서는 ggplot2 패키지를 사용하여 R에서 Gantt 차트를 만드는 방법을 설명합니다.
ggplot2를 사용하여 R에서 간트 차트 만들기
한 매장에서 직원 4명의 교대 근무 시작 시간과 종료 시간을 보여주는 다음 데이터 세트가 있다고 가정해 보겠습니다.
#create data frame
data <- data.frame(name = c('Bob', 'Greg', 'Mike', 'Andy'),
start = c(4, 7, 12, 16),
end = c(12, 11, 8, 22),
shift_type = c('early', 'mid_day', 'mid_day', 'late')
)
data
# name start end shift_type
#1 Bob 4 12 early
#2 Greg 7 11 mid_day
#3 Mike 12 8 mid_day
#4 Andy 16 22 late
각 작업자의 시작 및 종료 시간을 시각화하는 ggplot2를 사용하여 간트 차트를 만들려면 다음 코드를 사용할 수 있습니다.
#install (if not already installed) and load ggplot2 if(!require(ggplot2)){install.packages('ggplot2')} #create gantt chart that visualizes start and end time for each worker ggplot(data, aes(x=start, xend=end, y=name, yend=name, color=shift_type)) + geom_segment()
그러면 다음과 같은 간트 차트가 생성됩니다.
레이아웃을 몇 가지 조정하면 이 간트 차트를 훨씬 더 보기 좋게 만들 수 있습니다.
ggplot(data, aes(x=start, xend=end, y=name, yend=name, color=shift_type)) + theme_bw()+ #use ggplot theme with black gridlines and white background geom_segment(size=8) + #increase line width of segments in the chart labs(title='Worker Schedule', x='Time', y='Worker Name')
그러면 다음 그래프가 생성됩니다.
또한 차트에 사용할 정확한 색상을 설정하려면 다음 코드를 사용할 수 있습니다.
ggplot(data, aes(x=start, xend=end, y=name, yend=name, color=shift_type)) + theme_bw()+ #use ggplot theme with black gridlines and white background geom_segment(size=8) + #increase line width of segments in the chart labs(title='Worker Schedule', x='Time', y='Worker Name') + scale_color_manual(values = c('pink', 'purple', 'blue'))
그러면 다양한 교대 유형을 나타내는 분홍색, 보라색, 파란색의 다음 그래프가 생성됩니다.
맞춤 테마 사용
ggthemes 라이브러리의 사용자 정의 테마를 사용하면 더 나아갈 수 있습니다.
예를 들어, Wall Street Journal에서 영감을 받은 테마를 사용하는 간트 차트를 만들 수 있습니다.
#load ggthemes library library(ggthemes) #create scatterplot with Wall Street Journal theme ggplot(data, aes(x=start, xend=end, y=name, yend=name, color=shift_type)) + theme_bw()+ geom_segment(size=8) + labs(title='Worker Schedule', x='Time', y='Worker Name') + scale_color_manual(values = c('pink', 'purple', 'blue')) + theme_wsj() + theme(axis.title = element_text())
아니면 The Economist에서 영감을 받은 주제를 사용할 수도 있습니다.
ggplot(data, aes(x=start, xend=end, y=name, yend=name, color=shift_type)) +
theme_bw()+
geom_segment(size=8) +
labs(title='Worker Schedule', x='Time', y='Worker Name') +
scale_color_manual(values = c('pink', 'purple', 'blue')) +
theme_economist() +
theme(axis.title = element_text())
아니면 5시 38분 에서 영감을 받은 테마일 수도 있습니다.
ggplot(data, aes(x=start, xend=end, y=name, yend=name, color=shift_type)) +
theme_bw()+
geom_segment(size=8) +
labs(title='Worker Schedule', x='Time', y='Worker Name') +
scale_color_manual(values = c('pink', 'purple', 'blue')) +
theme_fivethirtyeight() +
theme(axis.title = element_text())
ggthemes 라이브러리에서 사용할 수 있는 전체 테마 목록은 설명서 페이지를 참조하세요.