티스토리 뷰
1. 데이터 수집
통합지리정보서비스 이용 ;
https://sgis.kostat.go.kr/view/index
library(readxl)
dir()
d1970<-read_excel("1970.xls")
d1980<-read_excel("1980.xls")
d1990<-read_excel("1990.xls")
d2000<-read_excel("2000.xls")
d2010<-read_excel("2010.xls")
d2020<-read_excel("2020.xls")
2. 데이터 살펴보기
# 4째열 연도 추가
d1960[4]<-1960
d1970[4]<-1970
d1980[4]<-1980
d1990[4]<-1990
d2000[4]<-2000
d2010[4]<-2010
d2020[4]<-2020
#행 붙이기
data <- rbind(d1960,d1970,d1980,d1990,d2000,d2010,d2020)
table(data[4])
summary(data)
colnames(data)<-c("Age","Male","Female","Year")
str(data)
data <- as.data.frame(data)
class(data)
3. 데이터 정제하기
###1. 문자열 제거
table(data$Age)
?sub() #sub(기존 패턴, 대체 패턴, 데이터)함수를 이용하여 필요없는 값 삭제
data$Age <- sub("세","", data$Age)
data$Age <- sub(" 이상", "", data$Age)
table(data$Age)
data$Age <- as.numeric(data$Age)
### 2. 열 추가
data.male <- data[,c("Age","Male","Year")]
colnames(data.male)<-c("Age","Population","Year","Sex")
data.female <- data[,c("Age","Female","Year")]
colnames(data.female)<-c("Age","Population","Year","Sex")
#남녀 데이터 합치기
data.new <-rbind(data.male,data.female)
table(data.new$Sex)
# 변수 타입 변환
data.new$Sex <-as.factor(data.new$Sex) #팩터형 변환
data.new$Year <-as.integer(data.new$Year) #정수형 변환
data.new$Population <-as.numeric(data.new$Population)#실수형 변환
str(data.new)
summary(data.new)
#x=0기준축을 중심으로 여성 우측, 남성 좌측 정렬하기
data.new$Population <- data.new$Population/10000 #만단위로 표시
data.new$Population <- ifelse(data.new$Sex=="male",-data.new$Population, data.new$Population)
4. 데이터 시각화 하기
library(ggplot2)
### 1. 피라미드 형태의 그래프
ggplot(data.new[data.new$Year=='1960',], aes(x=Population,y=Age, fill=Sex)) +
geom_bar(stat="identity")+
labs(title="대한민국 인구 피라미드(1960년)", x= "인구 수", y="연령")
#x축과 y축 변환
ggplot(data.new[data.new$Year=='1960',], aes(y=Population, x=Age, fill=Sex)) +
geom_bar(stat="identity") +
labs(title="대한민국 인구 피라미드(1960년)", x= "인구 수", y="연령")
#그래프 회전 : coord_filp()
ggplot(data.new[data.new$Year=='1960',], aes(y=Population, x=Age, fill=Sex)) +
geom_bar(stat="identity") +
coord_flip()+
labs(title="대한민국 인구 피라미드(1960년)", x= "인구 수", y="연령")
# 구분하여 도식화 : facet_grid(cols=vars(Year))
ggplot(data.new, aes(y=Population, x=Age, fill=Sex)) +
geom_bar(stat="identity") +
coord_flip()+
facet_grid(cols=vars(Year)) +
labs(title="대한민국 인구 피라미드", x= "인구 수", y="연령")
참고
측면(facets)으로 나누어 그리기
facet_wrap()로 일차원 측면 그래프 그리기
ggplot() +
geom_point(mapping=aes(x=displ, y=hwy), data=mpg) +
facet_wrap(~class, nrow = 2)
ggplot() +
geom_point(mapping=aes(x=displ, y=hwy), data=mpg) +
facet_wrap(~drv + year, nrow = 2)
facet_grid()로 이차원 측면 그래프 그리기
ggplot() +
geom_point(mapping=aes(x=displ, y=hwy), data=mpg) +
facet_grid(drv~cyl)
geom 함수의 순서와 그래프 계층
ggplot() + geom_smooth(mapping=aes(x=displ, y=hwy), data=mpg)
ggplot() +
geom_point(mapping=aes(x=displ, y=hwy), data=mpg) +
geom_smooth(mapping=aes(x=displ, y=hwy), data=mpg)
ggplot2 그래프의 종류
geom 함수함수도형도형의.속성
geom_bar() | Bar chart | color, fill, alpha |
geom_boxplot() | Box plot | color, fill, alpha, notch, width |
geom_density() | Density plot | color, fill, alpha, linetype |
geom_histogram() | Histogram | color, fill, alpha, linetype, binwidth |
geom_hline() | Horizontal lines | color, alpha, linetype, size |
geom_jitter() | Jittered points | color, size, alpha, shape |
geom_line() | Line graph | color, alpha, linetype, size |
geom_point() | Scatterplot | color, alpha, shape, size |
geom_rug() | Rug plot | color, side |
geom_smooth() | Fitted line | method, formula, color, fill, linetype, size |
geom_text() | Text annotations | 많은 옵션이 있으므로 도움말 참조 |
geom_violin() | Violin plot | color, fill, alpha, linetype |
geom_vline() | Vertical lines | color, alpha, linetype, size |
그래프 저장하기
p <- ggplot(mpg, aes(cty, hwy)) + geom_point()
ggsave(file="myplot.png", plot=p, width=5, height=4)
# 범례 설정
ggplot(data.new, aes(y=Population, x=Age, fill=Sex)) +
geom_bar(stat="identity") +
coord_flip()+ facet_grid(cols=vars(Year)) +
labs(title="대한민국 인구 피라미드", x= "인구 수", y="연령")+
theme(legend.position = "bottom")
### 2. 애니메이션
install.packages("gganimate")
library(gganimate)?gganimate::transition_time
#gganimate 중(::) transition_time 도움말
p <- ggplot(data.new, aes(y=Population, x=Age, fill=Sex)) +
geom_bar(stat="identity") +
coord_flip()
p + transition_time(Year) +
enter_fade() +
labs(title="대한민국 인구 피라미드: :{floor(frame_time)}", y= "인구 수", x="연령")
anim_save("population.gif")
728x90
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
반응형