R/R기초

R14_ interactive graph

Codezoy 2019. 10. 22. 11:29

# 인터렉티브 그래프
#패키지 plotly :  https://plot.ly/ggplot2/
# 주식 변동 그래프 만들 때 주로 사용 : http://rstudio.github.io/dygraphs/

install.packages('plotly')
library(plotly)

# 배기량(displ), 구동방식(drv)과 고속도로 연비(hwy)와의 관계
g = ggplot(data = mpg,   mapping = aes(x = displ, y = hwy, color = drv)) +   geom_point()


# plotly::ggplotly(ggplot객체)
ggplotly(g)                  # 그래프 상의 점이 가진 모든 정보를 보여줌


# 구동방식별 boxplot
g = ggplot(data = mpg, mapping = aes(x = drv, y = hwy)) +  geom_boxplot()
ggplotly(g)

#다이아몬드 도수분포표 + 막대 그래프
g <- ggplot(data=diamonds, mapping = aes(x= cut, fill = clarity))+ geom_bar(position = 'dodge')
ggplotly(g)


# 시간(date)에 따른 개인저축률(psavert)의 변화 - 선그래프
g <- ggplot(data= economics, mapping = aes(x = date, y = psavert )) +
  geom_line(color = 'darkblue')
ggplotly(g)

  • 패키지 쉽게 설치하기
Tools >> Install Packages




# 시계열 그래프를 그려주는 dygraphs 패키지에서 사용하는 데이터 타입.
eco_psavert <- xts(x = economics$psavert, order.by = economics$date)
str(eco_psavert)
dygraph(eco_psavert)



#실업률 변수 추가
economics <- ggplot2::economics
economics$unemprt <- (economics$unemploy / economics$pop)*100
head(economics$unemprt)


#시계열 그래프 그리기 위해서
eco_unemprt <- xts(x=economics$unemprt, order.by= economics$date)
str(eco_unemprt)
head(eco_unemprt)
dygraph(eco_unemprt)

# dygraph에서 시계열 그래프를 2개 이상 그리려면,
> data <- cbind(eco_psavert, eco_unemprt)         # 테이블 바인드
> str(data)
An ‘xts’ object on 1967-07-01/2015-04-01 containing:
  Data: num [1:574, 1:2] 12.6 12.6 11.9 12.9 12.8 11.8 11.7 12.3 11.7 12.3 ...
- attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr [1:2] "eco_psavert" "eco_unemprt"
  Indexed by objects of class: [Date] TZ: UTC
  xts Attributes:  
NULL

> head(data)
           eco_psavert eco_unemprt
1967-07-01        12.6    1.481541
1967-08-01        12.6    1.480562
1967-09-01        11.9    1.485589
1967-10-01        12.9    1.576933
1967-11-01        12.8    1.536858
1967-12-01        11.8    1.511592

>dygraph(data) %>% dyRangeSelector()
>> < 밑에 타임 스탬프 생성>