#### 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

+ Recent posts