## 
## Attaching package: 'dplyr'
## The following object is masked from 'package:MASS':
## 
##     select
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
##      이름  성별  키 몸무게 혈액형
## 1  일주영  남자 160     60      A
## 2  이주영  남자 170     70      A
## 3  삼주영  여자 180     80      B
## 4  사주영  남자 165     65     AB
## 5  오주영  여자 160     40     AB
## 6  육주영  여자 160     80      O
## 7  칠주영  여자 190     90      O
## 8  팔주영  여자 170     90      A
## 9  구주영  남자 160     50      B
## 10 십주영  남자 170     50      O

#————————————————– # 강의 과제(Assignment) 수행을 위한 실행 내용 #————————————————–

qplot과 ggplot의 레이어 구문 비교

1 : qplot과 ggplot

qplot(data = diamonds, x = carat, y = price, geom = “line”) ; ggplot(diamonds, aes(carat, price)) + geom_line();

2 : qplot(상대적으로 순서와 변수 명을 적시해야 함) ggplot

qplot(data = diamonds, x = carat, y = price, geom = c(“point”, “line”)) ; ggplot(diamonds, aes(carat, price)) + geom_line() + geom_point();

geom_point(color, shape(-8~25), size);

ggplot(diamonds, aes(carat, price)) + geom_line() + geom_point(col=“blue”, shape=-8, size=3);

scale_filee_brewer는 범주형 자료만 가능

ggplot(diamonds, aes(carat, price)) + geom_line() + geom_point(col=“grey”, shape=21, size=3)+scale_fill_brewer(palette=“Oranges”);

ggplot(iris, aes(Sepal.Width, Sepal.Length, fill=Species)) + geom_line(col=“red”) + geom_point(col=“grey”, shape=21, size=3)+scale_fill_brewer(palette=“Oranges”);

facet_grid(facet_wrap()) 사용

ggplot(iris, aes(Sepal.Width, Sepal.Length, fill=Species)) + geom_line(col=“red”) + geom_point(col=“grey”, shape=21, size=3)+scale_fill_brewer(palette=“Oranges”)+facet_wrap(Petal.Length~Species);

data Munging and Visualization : dplyr 패키지, MASS

install.packages(“MASS”); library(MASS); # Cars93 데이터 활용 library(dplyr); library(ggplot2); Cars93; str(Cars93);

Select columns of the dataframe

dplyr::select(mydata,mpg,cyl,wt) require(MASS) require(dplyr) mtcars %>% dplyr::select(mpg)

차량 유형 정보 확인

Cars93 %>% dplyr::select(Model, Type, Price, MPG.highway, Weight) Cars93 %>% filter(Type==“compact” | Type==“Large”)

mungdata <- Cars93 %>% dplyr::select(Model, Type, Price, MPG.highway, Weight) %>% filter(Type==“compact” | Type==“Large”)

변수의 변량에 따라서 크기를 달리하는 버블 차트 생성

ggplot(mungdata, aes(x=Weight, y=MPG.highway)) +geom_point(aes(size=Price), shape=21, color=“grey”, fill=“blue”, alpha=.5)

텍스트 정보 추가

ggplot(mungdata, aes(x=Weight, y=MPG.highway)) +geom_point(aes(size=Price), shape=21, color=“grey”, fill=“blue”, alpha=.5)+geom_text(aes(y=as.numeric(MPG.highway)-0.3), label=mungdata$Model, angle=45,size=4, color=“red”)

아래의 내용으로 저작

MASS::Cars93 활용

Cars93 데이터프레임의 열 설명

model :차량 모델

Type : 타입(small, Sporty, Compact, Midsize, Large, Van)

Min.Price : 최소가격(/$1,000) - 기본 사양

Max.Price : 최소가격(/$1,000) - 프리미엄 사양

1. 필요 패키지 및 로딩 : dplyr, ggplot2

2. 데이터 전처리 : Type, Model, Max.Price, Min.Price 변수 추출

2-1. dplyr::select 사용

d1 <- dplyr::select(Cars93, Type, Model, Max.Price, Min.Price) # 2-2. subset 사용 d1 <- subset(Cars93, select=c(“Type”, “Model”, “Max.Price”, “Min.Price”))

3. Type이 Large, Sporty, Van에 해당하는 자료만 추출

3-1. dplyr::filter 사용

d2 <- d1 %>% filter(Type==“Large” | Type == “Sporty” | Type==“Van”) # 3-1. subset 사용 d2 <- subset(d1, Type==“Large” | Type == “Sporty” | Type==“Van”)

4. 상위 6개 레코드 확인

head(d2);

5. ggplot 그리기(geom_point())

x축-최대가격, y축-모델, Type에 따른 모양 변화

ggplot(d2, aes(x=Max.Price, y=Model, shape=Type, color=Type))+geom_point(size=2)

6. y를 Max.Price 순으로 정렬 : reorder 사용

g1<- ggplot(d2, aes(x=Max.Price, y=reorder(Model, Max.Price), shape=Type, color=Type))+geom_point(size=3) g1;

7. 배경색 제거

g2 <- g1 + theme_bw(); g2;

8. x축 그리드(grid) 제거, y축 그리드(grid) 제거

g3 <-g2+ theme( panel.grid.major.x = element_blank(), panel.grid.minor.x = element_blank(), panel.grid.major.y = element_line(color=“grey”, linetype=“dashed”)) g3;

9. Type 별로 그리기 : facet_grid 사용

ggplot(d2, aes(x=Max.Price, y=reorder(Model, Max.Price), shape=Type, color=Type))+geom_point(size=3)+theme_bw()+theme( panel.grid.major.x = element_blank(), panel.grid.minor.x = element_blank())+facet_grid(Type~.)

10. Type 별로 구분된 모델별 Min.Price와 Max.Price 그리기

데이터 전처리 : 패키지 reshape2 사용

install.packages(“reshape2”); library(reshape2);

d2; md <- melt(d2, idvars=c(“Type, Model”)) Using Type, Model as id variables head(md);

11. 점까지만 선 그리기 : geom_segment() 사용

g1 <- ggplot(md, aes(x=value, y=reorder(Model, value))) + geom_segment(aes(yend=Model, xend=0)); g1;

12. Max, Min에 따라 모양 구분

g2 <- g1 + geom_point(size=3, aes(shape=variable)); g2;

13. Type 별로 그리기

13-1. 값이 없어도 y축의 모든 요소를 명기

g3 <- g2 + theme_bw() + theme( panel.grid.major.x = element_blank(), panel.grid.major.y = element_blank())+facet_grid(Type~.)+xlab(“Price($)”)+ylab(“Model”) g3;

13-2. 값이 없는 y축의 요소 제거

g3 <- g2 + theme_bw() + theme( panel.grid.major.x = element_blank(), panel.grid.major.y = element_blank())+facet_grid(Type~., scales=“free_y”, space=“free_y”)+xlab(“Price($)”)+ylab(“Model”) g3; #—————————————- # 14. 값에 따라 점의 크기가 변하는 그래프 버블 차트 생성 # MASS 데이터프레임 Cars93 활용 # dplyr 패키지의 전처리 함수 활용

14-1. 데이터프레임의 칼럼 선택 예시

예시

dplyr::select(mydata,mpg,cyl,wt) mtcars %>% dplyr::select(mpg)

14-2. Model, Type, Price, MPG.highway, Weight 필드 정보만 추출

Cars93 %>% dplyr::select(Model, Type, Price, MPG.highway, Weight)

14-3. Type이 compact나 Large인 차량 기종만 선별

Cars93 %>% filter(Type==“compact” | Type==“Large”)

14-4. 파이프 활용 결과를 변수 mungdata에 저장

mungdata <- Cars93 %>% dplyr::select(Model, Type, Price, MPG.highway, Weight) %>% filter(Type==“compact” | Type==“Large”)

14-5. 변수의 변량에 따라서 크기를 달리하는 버블 차트 생성

ggplot(mungdata, aes(x=Weight, y=MPG.highway)) +geom_point(aes(size=Price), shape=21, color=“grey”, fill=“blue”, alpha=.5)

14-6. 추가 텍스트 정보 삽입과 표기 형식 지정

ggplot(mungdata, aes(x=Weight, y=MPG.highway)) +geom_point(aes(size=Price), shape=21, color=“grey”, fill=“blue”, alpha=.5)+geom_text(aes(y=as.numeric(MPG.highway)-0.3), label=mungdata$Model, angle=45,size=4, color=“red”)

Assignment

입력 파일 man.csv 를 만들고 결과를 다음과 같은 차트를 생성 출력하시오.

입력 파일의 각 줄의 끝에 공백등이 포함될 경우 공백을 포함한 다른 변수로 취급하므로

입력 값 설정시 주의

1. man.csv를 읽어들여 변수 man 에 저장

man <- read.csv(“man.csv”, head = TRUE); man ;

man_gg <- ggplot(man, aes(x=몸무게, y=키, color=성별, shape=성별))+geom_point(size=7)+theme(text=element_text(size=20)); man_gg ;

man_gg_1 <- ggplot(man, aes(x=몸무게, y=키)) +geom_point(aes(color=성별, shape=혈액형), size=7)+theme(text=element_text(size=20)); man_gg_1 ;

man_gg_2 <- ggplot(man, aes(x=몸무게, y=키)) +geom_point(aes(color=성별, shape=혈액형), size=7)+theme(text=element_text(size=20))+ geom_text(aes(label=이름), vjust=1.1, color=“blue”, size=5)+theme_dark() man_gg_2 ;

##      이름  성별  키 몸무게 혈액형
## 1  일주영  남자 160     60      A
## 2  이주영  남자 170     70      A
## 3  삼주영  여자 180     80      B
## 4  사주영  남자 165     65     AB
## 5  오주영  여자 160     40     AB
## 6  육주영  여자 160     80      O
## 7  칠주영  여자 190     90      O
## 8  팔주영  여자 170     90      A
## 9  구주영  남자 160     50      B
## 10 십주영  남자 170     50      O