Load dataset từ googlesheet

Để thuận tiện vẽ timeline, chúng ta sẽ edit trên file googlesheet (chỗ nào cần xuống hàng trong đồ thị thì các bạn cho ctrl + enter), khi cần update thì sẽ điều chỉnh trên file googlesheet này rồi render lại file Rmarkdown là xong :)

Link: https://docs.google.com/spreadsheets/d/1k4NW4vP9OBy1FMNCNM3Zonp-O0xCXE80CoYeD9Hd3Cg/edit?usp=sharing

library("googlesheets4")
timeline_r <- read_sheet('1k4NW4vP9OBy1FMNCNM3Zonp-O0xCXE80CoYeD9Hd3Cg')
# nên verify ở một tài khoản gmail clone để thuận tiện edit dataset

# chuyển về vector ngày tháng
timeline_r$event_date <- ISOdate(timeline_r$event_date, 1, 1) # quy ước là ngày 1, tháng 1
timeline_r$event_date <- as.Date(timeline_r$event_date)

# chuyển về data frame
timeline_r <- as.data.frame(timeline_r)

# in dataset
options(width = 200) # in full table
timeline_r
##                                                                                    event_name event_date
## 1                                               Ngôn ngữ S được phát triển\nở Bell Labs (USA) 1975-01-01
## 2  John Chambers viết cuốn \n"The New S Language"\nđạt nền tảng cho\nlập trình S và R sau này 1988-01-01
## 3                  Ross Ihaka và Robert Gentleman\n(New Zealand) phát triển \nngôn ngữ R từ S 1993-01-01
## 4                                           R được phát hành\ntheo giấy phép\nmã nguồn mở GNU 1995-01-01
## 5    Bài báo chính thức về R\n"R: A Language for \nData Analysis and Graphics" \nđược công bố 1996-01-01
## 6                                             Hình thành CRAN, \nmailling list và R core team 1997-01-01
## 7                                                                 R 1.0.0 \nra mắt công chúng 2000-01-01
## 8                          Thành lập database \nBioconductor chứa package\nphân tích sinh học 2001-01-01
## 9                                     R 2.0.0 công bố\nhỗ trợ lazy loading\nvà xử lý big data 2004-01-01
## 10                                               Hadley Wickham phát triển\nggplot2 vẽ đồ thị 2007-01-01
## 11                                                          RStudio beta 0.92\nđược phát hành 2011-01-01
## 12                                                                   Phát triển shiny package 2012-01-01
## 13                                       R 3.0.0 phát hành\nhỗ trợ full cho\nkiến trúc 64 bit 2013-01-01
## 14                                                              Package tidyverse \nphát hành 2016-01-01
## 15                                        R 4.0.0 hỗ trợ \nfull UTF-8 giúp \ngõ tiếng Việt OK 2020-01-01

Vẽ đồ thị

library("timelineS") 
# Function gốc `timelineS`, mình copy function đó tạo thành v1 để thuận tiện điều chỉnh

timelineS_v1 <- function(df,
                         main = NA,
                         xlab = NA,
                         buffer.days = 600,
                         line.width = 5,
                         line.color = "gray44",
                         scale = "year",
                         scale.format = "%Y",
                         scale.font = 2,
                         scale.orient = 1,
                         scale.above = FALSE,
                         scale.cex = 1,
                         scale.tickwidth = 2,
                         labels = paste(df[[1]], df[[2]]),
                         label.direction = "downup",
                         label.length = c(0.5, 0.5, 0.8, 0.8),
                         label.position = c(1, 3
                         ), label.color = "gray44", label.cex = 0.8, label.font = 1,
                         label.angle = 0, pch = 20, point.cex = 1, point.color = "gray44") {
  if (!is.data.frame(df)) {
    stop("'df' must be a data frame")
  }
  df <- df[rowSums(is.na(df)) == 0, ]
  event.names <- df[[1]]
  event.dates <- df[[2]]
  if (label.direction == "downup") {
    d <- c(-1, 1)
    h <- 0
  } else if (label.direction == "updown") {
    d <- c(1, -1)
    h <- 0
  } else if (label.direction == "up") {
    d <- 1
    h <- -0.7
  } else if (label.direction == "down") {
    d <- -1
    h <- 0.7
  } else {
    d <- c(-1, 1)
    h <- 0
    print("incorrect label.direction, plot used default")
  }
  range.events <- range(min(event.dates) - buffer.days, max(event.dates) +
    buffer.days)
  r1 <- range.events[1]
  r2 <- range.events[2]
  plot(NA,
    ylim = c(-1, 1), xlim = range.events, ann = FALSE,
    axes = FALSE
  )
  title(main = main, xlab = xlab)
  points <- rep_len(d * label.length, length.out = nrow(df))
  events <- rep_len(label.position, length.out = nrow(df))
  segments(event.dates, h, event.dates, points + h, col = label.color)
  axis.Date(ifelse(scale.above == TRUE, 3, 1),
    at = seq(as.Date(paste0(
      lubridate::year(r1),
      "-", lubridate::month(r1), "-", 1
    )), as.Date(paste0(
      lubridate::year(r2),
      "-", lubridate::month(r2) + 1, "-", 1
    )), by = scale),
    format = scale.format, cex.axis = scale.cex, pos = h,
    lwd.tick = scale.tickwidth, col = line.color, font = scale.font,
    las = scale.orient
  )
  abline(h = h, lwd = line.width, col = line.color)
  points(
    x = event.dates, y = points + h, pch = pch, cex = point.cex,
    col = point.color
  )
  text(
    x = event.dates, y = points + h, labels = labels, cex = label.cex,
    pos = events, font = label.font, srt = label.angle
  )
  ### Đưa thông tin nguồn tham khảo
  text(x = min(event.dates) + 2500, y = -1,
       substitute(bold("Nguồn: Giorgi, F. M., Ceraolo, C., & Mercatelli, D. (2022).\nThe R Language: An Engine for Bioinformatics and Data Science. Life, 12(5), 648.\nsử dụng package 'timelineS' | đồ thị được vẽ bởi www.tuhocr.com")),
       srt = 0,
       pos = 3,
       cex = 0.7,
       col = "brown"
       )
}

Click vào hình để phóng to

timelineS_v1(timeline_r, 
             main = "Các cột mốc phát triển R",
             labels = paste(timeline_r[[1]], " ", "(", as.numeric(format(timeline_r[[2]], "%Y")), ")", sep = ""),
             label.direction = "updown",
             label.length = c(0.5, 0.5, 0.8, 0.8),
             label.position = c(3, 1),
             line.color = "blue",
             label.color = "blue",
             point.color = "blue",
             pch = 20)

Sơ kết

Trên đây là hướng dẫn cách vẽ timeline trong R, hỗ trợ chúng ta hệ thống hóa kiến thức theo sơ đồ thời gian. Để học R bài bản từ A đến Z, kính mời Bạn tham gia khóa học “HDSD R để xử lý dữ liệu” để có nền tảng vững chắc về R nhằm tự tay làm các câu chuyện dữ liệu của riêng mình!

Nội dung khóa học: www.tuhocr.com

Hành trình ngàn dặm bắt đầu từ bước chân đầu tiên.

ĐĂNG KÝ NGAY: https://www.tuhocr.com/register

Session info

sessionInfo()
## R version 4.2.1 (2022-06-23 ucrt)
## Platform: x86_64-w64-mingw32/x64 (64-bit)
## Running under: Windows 10 x64 (build 19041)
## 
## Matrix products: default
## 
## locale:
## [1] LC_COLLATE=English_United States.utf8  LC_CTYPE=English_United States.utf8    LC_MONETARY=English_United States.utf8 LC_NUMERIC=C                           LC_TIME=English_United States.utf8    
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
## [1] timelineS_0.1.1     googlesheets4_1.0.1
## 
## loaded via a namespace (and not attached):
##  [1] highr_0.9         cellranger_1.1.0  bslib_0.4.0       compiler_4.2.1    pillar_1.8.1      jquerylib_0.1.4   tools_4.2.1       digest_0.6.29     lubridate_1.8.0   gtable_0.3.1     
## [11] jsonlite_1.8.0    googledrive_2.0.0 evaluate_0.16     gargle_1.2.1      lifecycle_1.0.3   tibble_3.1.8      pkgconfig_2.0.3   rlang_1.0.6       cli_3.4.0         DBI_1.1.3        
## [21] rstudioapi_0.14   curl_4.3.2        yaml_2.3.5        xfun_0.33         fastmap_1.1.0     withr_2.5.0       httr_1.4.4        stringr_1.4.1     dplyr_1.0.10      knitr_1.40       
## [31] askpass_1.1       rappdirs_0.3.3    generics_0.1.3    fs_1.5.2          vctrs_0.5.1       sass_0.4.2        grid_4.2.1        tidyselect_1.1.2  glue_1.6.2        R6_2.5.1         
## [41] fansi_1.0.3       rmarkdown_2.16    ggplot2_3.4.0     purrr_0.3.4       magrittr_2.0.3    scales_1.2.1      htmltools_0.5.3   assertthat_0.2.1  colorspace_2.0-3  utf8_1.2.2       
## [51] stringi_1.7.8     munsell_0.5.0     openssl_2.0.3     cachem_1.0.6