한의대 생활/└ R studio 시각화

5. [] barplot with error bar []

2019. 1. 15. 23:18

R mark down으로 작성



bar plot with error bar

bar plot

par(mfrow = c(1,1))
barplot(c(1, 2, 3, 4)) # y값만 입력한 경우

barplot(c(1, 2, 3, 4), names.arg = c("A", "B", "C", "D")) # y값과 x축이름을 지정한 경우

데이터 가져와서, 각 칼럼들의 기준별 통계구하기

attach(iris)

head(iris)
str(iris)
## 'data.frame':    150 obs. of  5 variables:
##  $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
##  $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
##  $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
##  $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
##  $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
# bar의 높이(y값)으로 쓰일 각 칼럼의 <종별>  평균 계산하기
# aggregate( 통계구할 칼럼, 기준칼럼(list(col1, col2), 통계함수)
# -> 종을 기준으로 4개의 칼럼의 평균값 구하기
iris.mean <- aggregate(iris[, 1:4], iris["Species"], mean)
iris.mean
# bar의 error bar로 쓰일 각 칼럼 <종별> 표준편차 구하기
iris.sd <- aggregate(iris[,1:4], iris["Species"], sd)
iris.sd

표준편차와 평균df를 가지고, error bar의 위쪽, 아래쪽 좌표 계산해놓기

# df + aggregate로 구한 표준편차 df는 첫칼럼이 기준(종별)이다.
iris.sd 
# 기준칼럼 말고, 수치가 있는 [,2:5]칼럼만 가져와서
# error bar의 위쪽값과 아래쪽값을 구하자.
iris.sd.upper <- iris.mean[, 2:5] + iris.sd[, 2:5]
iris.sd.lower <- iris.mean[, 2:5] - iris.sd[, 2:5]

iris.sd.upper
iris.mean[, 2:5]
iris.sd.lower

평균을 좌표로 만들어서 barplot을 먼저 그려놓서 객체에 넣어두기(화살표의 기준점)

barplot( as.matrix(iris.mean[,2:5]), 
                   col=c("red", "blue", "purple"))

# beside = TRUE 를 넣어주면, 좌표로 그린 df의 row별로 
# barplot이 옆으로 그려지고, 
# beside = FALSE는 stacked로 그려진다.
barplot( as.matrix(iris.mean[,2:5]), 
         beside = TRUE,
         col=c("red", "blue", "purple"))

b <-barplot( as.matrix(iris.mean[,2:5]), 
         beside = TRUE,
         col=c("red", "blue", "purple"),
         ylim=c(0,8))

barplot을 그린 객체를 arrow()의 첫번째인자-화살표가 나가는 기준 으로 넣어서, barplot+arrow 동시에 그리기

# arrows는 이미 그려진곳에 그리는 것 같다. 안 그려놓으면 knit시 오류난다.
barplot( as.matrix(iris.mean[,2:5]), 
         beside = TRUE,
         col=c("red", "blue", "purple"),
         ylim=c(0,8))
arrows(b, as.matrix(iris.sd.upper), #기준, 화살표 끝의 좌표
      b, as.matrix(iris.sd.lower), #기준, 화살표 끝의 좌표
      angle = 90,                  # 몸통에서 나가는 화살표촉의 각도
      length = 0.05,               # 화살표 촉의 길이
      code = 3)                    # 화살표의 갯수 : 1시작점에 화살표 2끝점에 화살표 3 양쪽에 화살표


1. 데이터 준비(dataframe)

age <- c(18, 23, 25, 35, 65,
         54, 34, 56, 72, 19,
         23, 42, 18, 39, 37)
maxHR <- c(202, 186, 187, 180, 156,
           169, 174, 172 ,153, 199,
           193, 174, 198, 183, 178)

df <- data.frame(age, maxHR)
df
##    age maxHR
## 1   18   202
## 2   23   186
## 3   25   187
## 4   35   180
## 5   65   156
## 6   54   169
## 7   34   174
## 8   56   172
## 9   72   153
## 10  19   199
## 11  23   193
## 12  42   174
## 13  18   198
## 14  39   183
## 15  37   178


2. Linear Regression model 그리기

lm()함수를 사용하는데, y ~ X : X에 따른 y값(결과값)이다.

인자는 (y칼럼 ~ X칼럼, data = df ) 형태로 들어가야한다.

그 결과로는 계수(coefficients)가 나오는데

  1. 1차함수의 절편인 (intercept)와 2) 기울기가 나온다.
lm_result <- lm(maxHR ~ age, data = df)
lm_result
## 
## Call:
## lm(formula = maxHR ~ age, data = df)
## 
## Coefficients:
## (Intercept)          age  
##    210.0485      -0.7977
print(paste("y(maxHR) =",lm_result$coefficients[2],"x(age) +" ,lm_result$coefficients[1]))
## [1] "y(maxHR) = -0.797726564933042 x(age) + 210.048458424167"

y(maxHR) = -0.7977(age) + 210.0485


3. Visualization with ggplot

ggplot(data=df, aes(X축칼럼, x축칼럼)) +

geom_그래프종류() +

xlab(“x축이름”) + ylab(“y축이름”) +

ggtitle(“그래프이름”) +

stat_smooth(method = lm, level=0.95) # 오차를 최소로 만드는 선을 linear model로 추가, 신뢰도 0.95로 지정가능

#install.packages("ggplot2")
library(ggplot2)
ggplot(df, aes(age, maxHR)) +
  geom_point() +
  xlab("AGE") +
  ylab("Maxium Heart Rate") +
  ggtitle("Relation betweeb Maxium Heart Rate and Age") +
  stat_smooth(method = lm, level = 0.95)

x <- c(1:10)
y <- x^2 - x + 10
plot(x, y)

# type
plot(x, y, type = "p" ) # 점 출력 - default
plot(x, y, type = "n" ) # 아무것도 출력x
imageimage
plot(x, y, type = "S" ) # 계단식S : 해당값에서 올라갔다가 다음값으로 감
plot(x, y, type = "s" ) # 계단식s : 해당값에서 다음값으로 갔다가 올라감
imageimage
plot(x, y, type = "h" ) # bar와 비슷한데 선이 올라옴

image


# col
plot(x, y, type = "h", col = "blue" )
image

# pch - point의 모양바꾸기
plot(x, y, type = "p", col = "blue", pch = 1) # 동그라미 - default
plot(x, y, type = "p", col = "blue", pch = 2) # 세모
plot(x, y, type = "p", col = "blue", pch = 3) # +
plot(x, y, type = "p", col = "blue", pch = 4) # X
plot(x, y, type = "p", col = "blue", pch = 5) # 다이아몬드

# *** par(mfrow=c(nrow,ncol) + for()문을 이용하여 여러개 plot 동시에 그리기 ***
par(mfrow = c(2,4))
for(i in 1:8){
   plot(x, y, type ="p", col="blue", pch = i)
}
image


par(mfrow = c(2,4))
for(i in 9:16){
   plot(x, y, type ="p", col="blue", pch = i)
}

image


types = c("p", "l", "o", "b", "c", "s", "S", "h") # "o" = 점+선 overlap
par(mfrow = c(2,4))
for(i in 1:8){
   plot(x, y, type = types[i], col="blue")
}

image



#### ggvis 그래프 패키지 ####
# 칼럼명(변수) 앞에 ~가 있어야 변수인지 알아먹는다.***
# 겹쳐서 그릴 수 있는 것이 최대 장점이다.***

install.packages("ggvis")
library(ggvis)


#데이터 준비
mtcars

# 기본plot
plot(mtcars$mpg, mtcars$wt)
image

#### ***파이프라인 + ggvis ####
# 점찍기
mtcars %>%
   ggvis(~mpg, ~wt) %>% # 기본적으로 layer_point()로 점을 찍는다.
   layer_points() # 점찍기


  
# 라인그리기
mtcars %>%
   ggvis(~mpg, ~wt) %>%
   layer_lines()
image

# bar 그리기
mtcars %>%
   ggvis(~mpg, ~wt) %>%
   layer_bars()
image

# smooth 하게 이어주기
mtcars %>%
   ggvis(~mpg, ~wt) %>%
   layer_smooths()
image

# 점 + smooth 겹쳐 그리기
mtcars %>%
   ggvis(~mpg, ~wt) %>%
   layer_points()   %>%
   layer_smooths()
image


# 점에 색깔만 채우기( fill:= "색이름" )
# ggvis(, , fill:="red)  := 에 주의할 것.!
mtcars %>%
   ggvis(~mpg, ~wt, fill:="red") %>%
   layer_points()   %>%
   layer_smooths()

image



#*** x축, y축 칼럼 이외에 기준칼럼으로 점의 색 채우기( fill = ~칼럼명 )
mtcars %>%
   ggvis(~mpg, ~wt, fill = ~cyl) %>%
   layer_points()   %>%
   layer_smooths()

image


# *** 하지만, cyl은 현재 numeric(수치형, 연속형)의 자료형을 가지고 있어서,
# *** 4, 6, 8의 범주형을 가지고 있음에도 불구하고 그래프에서 <연속형 scalebar>를 가지고 있다.
# *** factor()범주형으로 cyl칼럼을 바꿔주고 다시 해보자.

mtcars$cyl <- factor(mtcars$cyl)
str(mtcars)
mtcars %>%
   ggvis(~mpg, ~wt, fill = ~cyl) %>%
   layer_points()   %>%
   layer_smooths()
### scalebar가 사라지고 범주형으로 딱딱 잘라서 보이는 범례가 나타난다.
image



# 축 격자들 더 촘촘하게 만들어주기 + 축 이름 달기 ***
# add_axis("x or y", title = "MPG", values = c(0:35) 구간에 찍힐 값 직접 명시 )
# add_axis("x or y", title = "MPG", subdivide = 4 기존 1구간안에 추가될 하위bar 개수)
mtcars %>%
   ggvis(~mpg, ~wt, fill = ~cyl) %>%
   layer_points()   %>%
   layer_smooths()  %>%
   add_axis("x", title = "MPG", values = c(0:35))

image



# 필요없는 구간이 나와서 범위 바꾸기
mtcars %>%
   ggvis(~mpg, ~wt, fill = ~cyl) %>%
   layer_points()   %>%
   layer_smooths()  %>%
   add_axis("x", title = "MPG", values = c(10:35))


# y축도 똑같이 해준다.
mtcars %>%
   ggvis(~mpg, ~wt, fill = ~cyl) %>%
   layer_points()   %>%
   layer_smooths()  %>%
   add_axis("x", title = "MPG", values = c(10:35)) %>%
   add_axis("y", title = "WT", subdivide = 4 ) # 4.5 와 5.0이 구간안에 .6 .7 .8 .9의 4개 하위bar 추가

image

#### dot chart ####

# 일반 plot()
x <- 1:10
y <- x-1
plot(x, y) #plot(y~x) 동일한 문법
plot(y~x)

#### 1. dotchart의 x(index)는 이산형( ex>문자열의 행이름 같은 or 수치형벡터 or 행렬 ) = 연속형 X ####
# *** x가 이산형태의 데이터야지 dotchart를 그릴 수 있다.
dotchart(y~x) #Error 'x'는 반드시 수치형 벡터 또는 행렬이어야 합니다.

#### 2. dotchart($칼럼인덱싱, labels, cex)는 < plot(x, y)과는 x축과 y축이 서로 바뀌어서 index가 y축에 > dot선을 가지고 나타난다. ####
# dotchart의 df자리에는 $컬럼인덱싱을 해주면, index가 (y축)으로서 간다.
#데이터 준비
mtcars # mpg(마일리지), cyl(실린더), gear(기어 수) 칼럼만 사용할 것이다.
mtcars$mpg

# 1) df의 한 칼럼(mpg칼럼)을 dotchart()에 넣어보자.
plot(mtcars$mpg) # plot()의 index는 각 차 이름(row명)가 숫자로서 나타남
image
dotchart(mtcars$mpg) #  index - 차이름(row.names)들이 y축으로 가며, 각 차이름들에 대해 dot들이 연결된다.
image

# 2) *** index(y축)가 행번호가 찍혀야하는데, 행 이름(문자열)이 기재되어있는 df라면 비어있게 되므로,  labels = row.names()라 기재해준다.
row.names(mtcars)
dotchart(mtcars$mpg, labels = row.names(mtcars))
image

# 3) *** y축(index) 글자의 크기를 줄일려면, cex = 0.7을 보통 주면 된다 *** ####
dotchart(mtcars$mpg, labels = row.names(mtcars), cex=0.7)
image


#### 3. 이제  dotchart()로 표현될 $mpg칼럼의 점들이 $cyl 컬럼에 대해서 어떻게 다른지 알아보자. ####
# 1) ***dotchat()에 그려지는 mpg칼럼에 대해 오름차순으로 먼저 정렬한다.
# *** df [ order ( $칼럼인덱싱 ),   ] *** 으로 한 칼럼에 대해 *** 오름차순 sort *** 시킨다.
carmpg <- mtcars[order(mtcars$mpg), ]
carmpg

# 2) ***mpg칼럼에 대해 오름차순 정렬된 df에  <- 기준 범주(그룹)를 적용할  칼럼 하나를 factor화(factor()) 하기 ####
참고) https://thebook.io/006723/ch02/03/06/ 
     # - factor()는 연속적인 - 수치형(my)연속형) (Numeric)과 상반되는 개념인 범주형(categorical)자료형으로
     # - 1) 순서를 둘 수 있는 순서형(Ordinal)과 2) 비교불가능한 범주인 명목형(Nominal)로 구분된다.
     # *** 실험결과 여기서는 factor() 안만들고 해도 상관없더라... ***

carmpg$cyl # cyl칼럼은 8 or 6 or 4이다.***연속형의 값이 아니라, 각각을 <구분해주는 요소(Factor)>들을 의미한다. ex> 남/여  1/2는  값의 크고작은 수치가 중요한게 아니라 <서로를 구분해주는 카테고리형, 범주형의 Factor>이다.
carmpg$cyl <- factor( carmpg$cyl )

# factor화된 것 확인
class(carmpg$cyl) # "factor"
# my)
sapply(carmpg, FUN = "class")

# 3) dotchart()에 그려지는 칼럼(mpg)에 대해 sort한 새로운df를 dotchart()그리기
dotchart(carmpg$mpg, labels = row.names(carmpg), cex=0.7 )

# 4) *** dotchart 칼럼(mpg)에 대해,  범주를 두고 싶은 칼럼(cyl)의 값 별로 -> 새로운 color칼럼 만들기
#cyl칼럼의 요소들 확인해보기
table(carmpg$cyl) # 4 /6 /8 종류가 있다.
# ***color칼럼 <생성과 동시에 &칼럼인덱싱> + 행인덱싱자리에   범주적용컬럼의 각별로 조건문인덱싱  = color값 문자열 대입
carmpg$color [ carmpg$cyl == 4 ] <- "blue"
carmpg$color [ carmpg$cyl == 6 ] <- "green"
carmpg$color [ carmpg$cyl == 8 ] <- "red"


# 5) ***cyl값에 대한 color칼럼을 dotchart()의 color=인자로 넣어준다.
dotchart(carmpg$mpg, labels = row.names(carmpg), cex=0.7, color=carmpg$color )
image

# 6) *** 그래프보고 해석해보기
# - cyl 8개 짜리(=빨간색)일수록 mpg가낮은 편이다.
# - cyl 4개 짜리일수록 mpg가 높은 편이다.


# 7) *** cyl값(4, 6, 8)별로 그룹을 나눠서 dotchart()보기 groups = 그룹 나누는 기준이 될 $칼럼
dotchart(carmpg$mpg, labels = row.names(carmpg),
          groups = carmpg$cyl, cex=0.7, color=carmpg$color )
image

# 8) main인자로 dotchart 제목 주기
dotchart(carmpg$mpg, labels = row.names(carmpg),
          groups = carmpg$cyl, cex=0.7, color=carmpg$color,
          main = "Milage depending on numbers of cylinder")

# 9) xlab인자로 dotchart x축 label 주기
dotchart(carmpg$mpg, labels = row.names(carmpg),
          groups = carmpg$cyl, cex=0.7, color=carmpg$color,
          main = "Milage depending on numbers of cylinder",
          xlab = "Milage per Gallon")

image

image


### 최종해석 : cyl와 milage는 반비례하는 경향이 있다.

+ Recent posts