2-2 ggplot - 산점도, bar차트, boxplot / plotly

ggplot - 산점도1

  • 도화지 : g <- ggplot(data, aes( 칼럼명1, 칼럼명2 ))
  • 그림1) 산점도 : g(data,aes(숫자1,숫자2)) + geom_point(aes( ))
  • 그림의 aes안에 colour, shape = factor(범주칼럼)으로 범주별 확인가능
  • 그림의 aes안에 size, alpha = 숫자형칼럼으로 scale범주별 확인가능
  • 그림의 aes안에 colour가 숫자형칼럼(factor()도 x)인 경우, scale바의 옵션을 지정해줄 수 있다. scale_colour_gradient(low = “red”, high = “green” )도
# install.packages("ggplot2")
library(ggplot2)

#  데이터 준비
data(mtcars)
View(mtcars)

# 1. 도화지 그리기
ggplot(mtcars, aes(wt, mpg))

# 2. 도화지에 산점도 그리기 + 색/모양으로 범주별로 보기
ggplot(mtcars, aes(wt, mpg)) +
  geom_point( aes( colour = factor(vs),
                   shape  = factor(cyl)) )

#  3. 도화지에 산점도 그리기 + 색/모양으로 범주별 + *size로 숫자형 칼럼을 scale로 
ggplot(mtcars, aes(wt, mpg)) +
  geom_point(aes(colour = factor(vs),shape=factor(cyl),size=qsec)) 

# 4. 도화지 + 산점도 + 색/모양으로로 범주별 + size로 숫자형칼럼을 scale로 + alpha로 숫자형 칼럼을 scale로 
#+ alpha
ggplot(mtcars, aes(wt, mpg)) +
  geom_point(aes(colour = factor(vs),shape=factor(cyl),size=qsec,alpha=wt))

# 5. colour가 숫자형칼럼(factor()도 x)인 경우, scale바의 옵션을 지정해줄 수 있다.
ggplot(mtcars, aes(wt, mpg)) +
  geom_point(aes(colour = disp,shape=factor(cyl),size=qsec,alpha=wt)) +
  scale_colour_gradient(low = "red")

ggplot(mtcars, aes(wt, mpg)) +
  geom_point(aes(colour = disp,shape=factor(cyl),size=qsec,alpha=wt)) +
  scale_colour_gradient(low = "red",high="green")

산점도 2 - facet_grid( ~ )범주별로 그림쪼개서 보기

  • 도화지는 변수에 담아둘 수 있다.
  • 산점도가 겹치는 경우 alpha 를 통해 투명도를 준다.
  • 범주별로 그림쪼개서 볼때, 앞의 범주( 범주칼럼 ~ .)는 가로방향으로 쪼갠다.
  • 범주별로 그림쪼개서 볼때, 뒤의 범주( . ~ 범주칼럼)는 세로방향으로 쪼갠다.
  • facet_grid( ~ )로 나눠봤을 때, 빈 그림이 존재하면 facet_wrap으로
    앞범주 X 뒷범주의 조합별로 산점도를 그리자 + ncol 도 입력가능하다.
# mpg 데이터(내장)
View(mpg)

# 숫자칼럼2개 -> 산점도 도화지
g <- ggplot(mpg, aes(displ, hwy))

# 숫자들이 겹치느 경우, alpha를 주어 겹치는 부분을 나타낸다.
g + geom_point(alpha=1/3) 

# facet_grid( ~ )로 범주칼럼을 주면 범주별로 앞(가로방향으로) , 뒤(세로방향으로) 쪼개서 볼 수 있다.
g + geom_point(alpha=1/3) + facet_grid(cyl ~ . )

g + geom_point(alpha=1/3) + facet_grid(. ~  cyl)

g + geom_point(alpha=1/3) + facet_grid(cyl ~  class)

# 만약 산점도가 범주별로 빈값이 존재한다면 -> facet_wrap( ~ , ncol=)을 쓰자.
# 앞 범주 X 뒷 범주의 조합으로 쪼개준다.
g + geom_point(alpha=1/3) + facet_wrap(cyl ~  class)

g + geom_point(alpha=1/3) + facet_wrap(cyl ~  class, ncol = 3)

ggplot - bar chart

  • barchart는 범주별 빈도를 보는 것이다.
  • 도화지는 ggplot(df, aes( facotr(범주칼럼) )) * 범주칼럼이라도 factor()로 싸준다.
  • 그림안에 aes없이 바로 witdh = 로 너비를 조절한다 (높이는 빈도가 책임)
  • 그림안의 aes()에 colour = factor(범주칼럼)으로 테두리색으로 범주별 범주빈도를 본다.
  • 그림안의 aes()에 fill = factor(범주칼럼)으로 stacked된 막대색으로 범주별 범주빈도를 본다.

  • 추가적인 + coord_flip() 으로 가로세로반전해준다.

# 범주칼럼1개에 대한 빈도 : geom_bar()
c<-ggplot(mtcars, aes(factor(cyl)))
c+geom_bar()

# bar의 너비 조절하기 witdh옵션
c + geom_bar(width=0.5)

# aes(colour = factor(범주칼럼))으로 테두리색으로 범주별 barchart(범주별 빈도)를 본다.
# 만약 같은 범주를 준다면, x축의 범주와 테두리색의 범주가 같을 것이다.
c + geom_bar(width = 0.5, aes( colour = factor(cyl) ) )

# aes(fill = factor(범주칼럼))으로 stacked로 나눠진 막대 색으로   범주별  barchart(범주별 빈도)를 본다.
c + geom_bar(width = 0.5, aes( colour = factor(cyl),
                               fill =  factor(am)) )

c + geom_bar(width = 0.5, aes( colour = factor(cyl),
                               fill =  factor(am)) ) + coord_flip()

ggplot - boxplot

  • 기본 boxplot은 숫자형칼럼의 분포를 보는 것이나
  • geom_boxplot()은 기본적으로 범주별 숫자칼럼의 분포를 보는 도화지를 aes에 그린다. ggplot( df, aes(범주칼럼, 숫자칼럼))
  • 그림은 geom_boxplot()으로 그린다.

  • ** 더이상 범주추가가 없는 경우 - width, color(테두리색), fill(박스색), outlier의 색/모양을 준다.

  • ** 범주를 추가하고 싶은 경우 2가지 방법
  1. 그림안의 aes()안에 colour = factor() or fill = factor() 로 준다.
  2. facet_grid()로 범주별로 그림을 쪼개준다.
  • 선을 추가하고 싶을때는 geom_hline() 혹은 geom_vline()을 + 한다(abline대체)
# 데이터 준비
setwd("C:/Users/is2js/python_da/deep analysis(논문용 설문지 분석)")
sens = read.csv('sens_for_r.csv', header = T)

# 데이터 확인 - 범주2, 숫자1
dim(sens)
## [1] 387   3
head(sens)
##   Kind.of.medicinal.herbs Sensitivity              Group
## 1                      SA        0.95 Ph.D. of Herbology
## 2                      SA        0.95 Ph.D. of Herbology
## 3                      SA        1.00 Ph.D. of Herbology
## 4                      SA        0.95 Ph.D. of Herbology
## 5                      SA        0.90 Ph.D. of Herbology
## 6                      SA        0.95 Ph.D. of Herbology
summary(sens)
##  Kind.of.medicinal.herbs  Sensitivity                   Group    
##  AC :129                 Min.   :0.000   KMD               : 36  
##  AMC:129                 1st Qu.:0.650   Ph.D. of Herbology: 18  
##  SA :129                 Median :0.800   Undergraduates    :333  
##                          Mean   :0.757                           
##                          3rd Qu.:0.950                           
##                          Max.   :1.000
str(sens)
## 'data.frame':    387 obs. of  3 variables:
##  $ Kind.of.medicinal.herbs: Factor w/ 3 levels "AC","AMC","SA": 3 3 3 3 3 3 2 2 2 2 ...
##  $ Sensitivity            : num  0.95 0.95 1 0.95 0.9 0.95 1 1 0.95 0.95 ...
##  $ Group                  : Factor w/ 3 levels "KMD","Ph.D. of Herbology",..: 2 2 2 2 2 2 2 2 2 2 ...
apply(is.na(sens), MARGIN = 2, FUN='sum')
## Kind.of.medicinal.herbs             Sensitivity                   Group 
##                       0                       0                       0
# summarizeColumns(sens)

View(sens)

# 기본 범주-숫자형의    범주별 boxplot(숫자의 분포)
boxplot( Sensitivity ~ Group,
data= sens,
notch = TRUE,
col = "orange") 
## Warning in bxp(list(stats = structure(c(0.1, 0.55, 0.825, 0.9, 1, 0.75, :
## some notches went outside hinges ('box'): maybe set notch=FALSE

# ggplot - geom_boxplot(범주칼럼, 숫자칼럼, fill = 범주칼럼 or 새로운범주칼럼)
g <- ggplot(sens, aes(Group, Sensitivity))
g + geom_boxplot()

# (더이상의 추가 범주가 없을 때!)barplot처럼 그림의 aes 바깥에서 바로 width + fill ='박스색', color='테두리색'을 그린다.
g <- ggplot(sens, aes(Group, Sensitivity))
g + geom_boxplot(width = 0.3, color = 'darkslategrey', fill ='orange')

# 아웃라이어들에 대한 색과 모양도 지정해줄 수 있다.
g + geom_boxplot(width = 0.3, color = 'darkslategrey', fill ='orange',
                 outlier.color = 'black',outlier.shape = 1)

# (추가범주 방법1) 그림안의 aes()에서 colour/fill를 준다는 것은 테두리/박스색 별로 범주를 추가해주는 것이다.
# 이때는, aes()바깥의 color, fill을 삭제해야한다.
g + geom_boxplot(width = 0.3, aes(colour = factor(Kind.of.medicinal.herbs)))

g + geom_boxplot(width = 0.3, aes(fill = factor(Kind.of.medicinal.herbs)))

# (추가범주 방법2) 그림을 짤라서 범주를 주고 싶다면 facet_grid를 쓴다.
g + geom_boxplot(width = 0.3, color = 'darkslategrey', fill ='orange') +
  facet_grid(.~Kind.of.medicinal.herbs)

# ggplot에서 새로운 선을 주고 싶을 땐 geom_hline/geom_vline으로 추가해준다.
# 여기서는 facet_grid로 범주까지 나뉘어져있으니, 그 범주를 주어 3개다 그이게 한다.
# 라인의 방향에 따라 y/xintercept를 준다. 
g + geom_boxplot(width = 0.3, color = 'darkslategrey', fill ='orange') +
  facet_grid(.~Kind.of.medicinal.herbs)  +
  geom_hline(aes(yintercept = mean(Sensitivity), group = Kind.of.medicinal.herbs), colour = 'red')

g + geom_boxplot(width = 0.3, color = 'darkslategrey', fill ='orange') +
  facet_grid(.~Kind.of.medicinal.herbs)  +
  geom_vline(aes(xintercept = mean(Sensitivity), group = Kind.of.medicinal.herbs), colour = 'green')


+ Recent posts