Link hướng dẫn về plotly: https://cran.r-project.org/web/packages/plotly/plotly.pdf

1 Bubble chart

Cú pháp:

plot_ly(data, x, y, color, colors, mode, type, text, size, ...)

Giải thích Argument:

  • data: Dữ liệu trục sử dụng để visualize.

  • x: Trục x.

  • y: Trục y.

  • color: Màu sắc được chia theo nhóm biến nào.

  • colors: Giá trị hex của màu sắc theo nhóm.

  • mode: Kiểu đồ thị là gì gồm: barchart, scatter, cicle, line, …

  • type: Loại đồ thị biểu diễn là gì: Marker, line, barchart,…

  • size: Kích thước hiển thị từng từng điểm.

  • text: Giá trị text hiện thị khi hover chuột lên đồ thị.

library(dplyr)
library(tidyr)
library(plotly)

data <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv")

data_2017 <- data[which(data$year == 2007),]
data_2017$size <- sqrt(data_2017$pop)

plot_ly(data_2017, x = ~gdpPercap, y = ~lifeExp, type = 'scatter', 
        mode = 'markers', 
        marker = list(symbol = 'circle', sizemode = 'diameter',
                      line = list(width = 2, color = '#FFFFFF')),
        size = ~size, color = ~continent,
        text = ~paste0('Country:', country, '<br>Life Expectancy:', lifeExp, '<br>GDP:', gdpPercap,
                      '<br>Pop.:', pop)) %>% 
  layout(title = 'Life Expectancy v. Per Capita GDP, 2007',
         xaxis = list(title = 'GDP per capital (2000 dolars)',
                      gridColor = 'white',
                      zerolinewidth = 1,
                      ticklen = 5,
                      gridwidth = 2),
         yaxis = list(title = 'Life Expectancy (years)',
                      gridColor = 'white',
                      zerolinewidth = 1,
                      ticklen = 5,
                      gridwidth = 2),
         paper_bgcolor = 'rbg(243,243,243)',
         plot_bgcolor = 'rbg(243,243,243)')
#We also can change color for buble
plot_ly(data_2017, x = ~gdpPercap, y = ~lifeExp, type = 'scatter', 
        mode = 'markers', 
        marker = list(symbol = 'circle', sizemode = 'diameter',
                      line = list(width = 2, color = '#FFFFFF')),
        size = ~size, color = ~continent,
        colors = c('red','blue','yellow','green','grey'),
        text = ~paste0('Country:', country, '<br>Life Expectancy:', lifeExp, '<br>GDP:', gdpPercap,
                      '<br>Pop.:', pop)) %>% 
  layout(title = 'Life Expectancy v. Per Capita GDP, 2007',
         xaxis = list(title = 'GDP per capital (2000 dolars)',
                      gridColor = 'white',
                      zerolinewidth = 1,
                      ticklen = 5,
                      gridwidth = 2),
         yaxis = list(title = 'Life Expectancy (years)',
                      gridColor = 'white',
                      zerolinewidth = 1,
                      ticklen = 5,
                      gridwidth = 2),
         paper_bgcolor = 'rbg(243,243,243)',
         plot_bgcolor = 'rbg(243,243,243)')

2 Barchart

Chúng ta chỉ cần thay đổi type từ ‘scatter’ thành ‘bar’ và sử dụng add_trace() để tạo add thêm cột mới. Có thể chuyển từ dạng group theo nhóm thành stack bằng cách khai báo ở argument barmode trong layout từ ‘group’ thành ‘stack’.

library(dplyr)
library(tidyr)

pop <- data %>% filter(country %in% c('Vietnam','Philippines')) %>% 
  select(year, country, pop) %>% 
  spread(key = country, value = pop)

pop$year <- as.character(pop$year)

#Visualize population in group graph
pop %>% plot_ly(x = ~ year, y = ~ Vietnam, type = 'bar', name = 'Vietnam') %>%
  add_trace(y = ~ Philippines, name = 'Philippines') %>% 
  layout(title = 'Population Viet Nam & Philippines',
         yaxis = list(title = 'Population'),
         barmode = 'group',
         paper_bgcolor = 'rbg(243,243,243)',
         plot_bgcolor = 'rbg(243,243,243)')
#Stack graph
pop %>% plot_ly(x = ~ year, y = ~ Vietnam, type = 'bar', name = 'Vietnam') %>%
  add_trace(y = ~ Philippines, name = 'Philippines') %>% 
  layout(title = 'Population Viet Nam & Philippines',
         yaxis = list(title = 'Population'),
         barmode = 'stack',
         paper_bgcolor = 'rbg(243,243,243)',
         plot_bgcolor = 'rbg(243,243,243)')
#Add boundary line
pop %>% plot_ly(x = ~ year, y = ~ Vietnam, type = 'bar', name = 'Vietnam',
            marker = list(color = 'rbg(243,43,100,0.7)',
              line = list(color = 'rgb(8,48,107)',
                          width = 1.5)
            )) %>%
  add_trace(y = ~ Philippines, name = 'Philippines',
            marker = list(color = 'rgb(158,202,225,0.7)',
              line = list(color = 'rgb(8,48,107)',
                          width = 1.5)
            )) %>% 
  layout(title = 'Population Viet Nam & Philippines',
         yaxis = list(title = 'Population'),
         barmode = 'group',
         paper_bgcolor = 'rbg(200,200,200)',
         plot_bgcolor = 'rbg(200,200,200)')

3 Point

#Draw normal scatter point.
(p <- plot_ly(iris, x = ~ Sepal.Length, y = ~ Petal.Length,
        marker = list(size = 10,
                      color = 'rgba(255, 183, 193, 0.9)',
                      line = list(color = 'rgba(152, 0, 0, 0.8)',
                                  width = 2)
                      )))
trace_0 <- rnorm(100,5)
trace_1 <- rnorm(100,0)
trace_2 <- rnorm(100,-5)

x <- c(1:100)

data <- data.frame(x, trace_0, trace_1, trace_2)

#Draw multiple lines and markers in same plot.
(p <- plot_ly(data, x = ~ x, y = ~ trace_0, type = 'scatter', mode = 'lines') %>% 
    add_trace(y = ~ trace_1, mode = 'markers+lines') %>% 
    add_trace(y = ~ trace_2, mode = 'markers',
              marker = list(color = 'red')))
#Classify point in group
(p <- plot_ly(iris, x = ~ Sepal.Length, y = ~ Petal.Length, color = ~ Species))
#Change the marker
(p <- plot_ly(iris, x = ~ Sepal.Length, y = ~ Petal.Length, symbol = ~ Species, symbols = c('circle','x','o'), 
              marker = list(size = 10, line = list(color = 'white', width = 2))))
#Add line regression in point
fit <- lm(data = iris, Petal.Length ~ Sepal.Length)

(p <- plot_ly(iris, x = ~ Sepal.Length) %>% 
    add_markers(y = ~ Petal.Length) %>% 
    add_lines(x = ~ Sepal.Length, y = fitted(fit)))
#Add polygon quadratic regression in point
fit <- lm(data = iris, Petal.Length ~  poly(Sepal.Length,2))

(p <- plot_ly(iris, x = ~ Sepal.Length) %>% 
    add_markers(y = ~ Petal.Length) %>% 
    add_lines(x = ~ Sepal.Length, y = fitted(fit)))
#Add polygon third degree regression in point
fit <- lm(data = iris, Petal.Length ~  poly(Sepal.Length,3))

(p <- plot_ly(iris, x = ~ Sepal.Length) %>% 
    add_markers(y = ~ Petal.Length) %>% 
    add_lines(x = ~ Sepal.Length, y = fitted(fit)))