1. Nguồn dữ liệu Đậu mùa khỉ sử dụng để phân tích:

Dữ liệu các trường hợp Đậu mùa khỉ được lấy từ tài nguyên Github. Dữ liệu ở đây được cập nhật hàng ngày và có bản báo cáo tóm tắt cập nhật tình hình Monkeypox.

License and attribution:

This repository and data exports (except files in the ecdc folder) are published under the CC BY 4.0 license.

Please cite as: “Global.health Monkeypox (accessed on YYYY-MM-DD)”

&

Kraemer, Tegally, Pigott, Dasgupta, Sheldon, Wilkinson, Schultheiss, et al. Tracking the 2022 Monkeypox Outbreak with Epidemiological Data in Real-Time. The Lancet Infectious Diseases. https://doi.org/10.1016/S1473-3099(22)00359-0.

Sử dụng các packages sau để phân tích:

  1. “read_csv”;

  2. “dplyr”;

  3. “ggplot2”.

# Clear E environment: 
rm(list = ls())

# Load data from https://github.com/globaldothealth/monkeypox
readr::read_csv("https://raw.githubusercontent.com/globaldothealth/monkeypox/main/latest.csv") -> monkeypox

# load dplyr package: 
library(dplyr)

# load ggplot2 package: 
library(ggplot2)

Trước hết xem qua bộ dữ liệu:

# Xem qua bo du lieu: 
  
monkeypox  %>% 
  group_by(Status) %>% 
  count()
## # A tibble: 4 × 2
## # Groups:   Status [4]
##   Status         n
##   <chr>      <int>
## 1 confirmed  21125
## 2 discarded    349
## 3 omit_error   273
## 4 suspected   1679
monkeypox  %>% 
  group_by(Country) %>% 
  count()
## # A tibble: 105 × 2
## # Groups:   Country [105]
##    Country        n
##    <chr>      <int>
##  1 Andorra        3
##  2 Argentina     22
##  3 Australia     46
##  4 Austria       99
##  5 Bahamas        1
##  6 Bangladesh     1
##  7 Barbados       1
##  8 Belgium      393
##  9 Benin          3
## 10 Bermuda        1
## # … with 95 more rows
## # ℹ Use `print(n = ...)` to see more rows
# SX theo thu tu

monkeypox  %>% 
  group_by(Country) %>% 
  count(sort = TRUE)
## # A tibble: 105 × 2
## # Groups:   Country [105]
##    Country                              n
##    <chr>                            <int>
##  1 United States                     4866
##  2 Spain                             3924
##  3 Germany                           2540
##  4 England                           2325
##  5 France                            1845
##  6 Democratic Republic Of The Congo  1476
##  7 Brazil                            1015
##  8 Netherlands                        878
##  9 Canada                             831
## 10 Portugal                           633
## # … with 95 more rows
## # ℹ Use `print(n = ...)` to see more rows
monkeypox  %>% 
  group_by(Gender) %>% 
  count() 
## # A tibble: 5 × 2
## # Groups:   Gender [5]
##   Gender     n
##   <chr>  <int>
## 1 female    17
## 2 Female     1
## 3 male    1700
## 4 Male      20
## 5 <NA>   21688
# --> Kq cho ra cac chi so khac nhau --> can ma hoa lai 

Kết quả biến số “Gender” cho ra nhiều cách nhập text khác nhau -> Cần mã hoá lại để thống nhất 1 code trước khi phân tích.

2. Kết quả phân tích

2.1. Top 12 Quốc gia có số trường hợp mắc cao nhất:

Sử dụng hàm pipe, filter, group_by, count, “ungroup”, slice, pull

# List of top-12 nations by confirmed cases: 
monkeypox %>% 
  filter(Status == "confirmed") %>% 
  group_by(Country)  %>% 
  count(sort = TRUE) %>%  # Tới đây là đã tạo được 1 data frame rồi. Nhưng nếu ko ungroup thì nó vẫn bị chi phối bởi lệnh "group_by"  --> để an toàn thì ngay sau đó cần sử dụng "ungroup"
  ungroup ()  %>% 
  slice(1:12)  %>% 
  pull(Country) -> top12 # Tạo ra 1 vector 
  
# Calculate daily cases by nation: 
monkeypox %>% 
  filter(Status == "confirmed") %>% 
  filter(Country %in% top12)  %>% 
  group_by(Country, Date_confirmation) %>% 
  summarise(daily_cases = n()) %>% 
    ungroup() -> df_daily_cases

# sx theo thứ tự ngày 
df_daily_cases  %>% 
  group_by(Country) %>% 
  arrange(Date_confirmation)
## # A tibble: 420 × 3
## # Groups:   Country [12]
##    Country       Date_confirmation daily_cases
##    <chr>         <date>                  <int>
##  1 England       2022-05-06                  1
##  2 England       2022-05-12                  1
##  3 England       2022-05-13                  1
##  4 England       2022-05-15                  4
##  5 Portugal      2022-05-17                  3
##  6 England       2022-05-18                  2
##  7 Portugal      2022-05-18                 11
##  8 Spain         2022-05-18                  7
##  9 United States 2022-05-18                  1
## 10 Belgium       2022-05-19                  1
## # … with 410 more rows
## # ℹ Use `print(n = ...)` to see more rows

2.2. Xu hướng dịch (Monkeypox Trend)

2.2.1. Trình bày theo từng Quốc gia (Top 12)

# Trình bày theo từng Quốc gia 

df_daily_cases  %>% 
  ggplot(aes(x = Date_confirmation, y = daily_cases, group = Country, color = Country)) + 
geom_line() +  # KQ hơi rối mắt --> Dùng lệnh sau tiếp theo để bóc tách từng QG ra từng ô, 
facet_wrap(~ Country) # Vẫn còn có Legend mà giờ thì ko cần thiết --> Bỏ đi bằng thêm "FALSE" 

df_daily_cases  %>% 
  ggplot(aes(x = Date_confirmation, y = daily_cases, group = Country, color = Country)) + 
geom_line(show.legend = FALSE) +  
facet_wrap(~ Country) # Nhìn phân bố số ca của mỗi nước khác nhau --> 1 số QG mắc ít rất khó nhìn --> Cần để scale free 

df_daily_cases  %>% 
  ggplot(aes(x = Date_confirmation, y = daily_cases, group = Country, color = Country)) + 
geom_line(show.legend = FALSE) +  
facet_wrap(~ Country, scales = "free")

df_daily_cases  %>% 
  ggplot(aes(x = Date_confirmation, y = daily_cases, group = Country, color = Country)) + 
geom_line(show.legend = FALSE, size =1) + # Size là kích thước đường line 
  facet_wrap(~ Country) +
  labs(title = "Số ca mắc Đậu mùa khỉ ở Top 12 Quốc gia") + 
  theme (axis.title = element_blank()) # Element_blank để loại bỏ 

Kết quả cho ra phân bố biểu đồ ngẫu nhiên, không theo thứ tự

Q1: sx các biểu đồ theo rank? Đã được thực hiện bên dưới:

2.2.2. Sắp xếp các biểu đồ lines Top 12 QG theo thứ tự cao-thấp

Cách 1: Tạo thêm 1 cột Country sx theo top12

df_daily_cases  %>% 
  mutate (Country = factor(Country, levels = top12)) %>%  # Phai chuyen doi dang bien Country tu Chr sang Factor 
  ggplot(aes(x = Date_confirmation, y = daily_cases, group = Country, color = Country)) + 
geom_line(show.legend = FALSE, size =1) + 
  facet_wrap(~ Country) +
  labs(title = "Số ca mắc Đậu mùa khỉ ở Top 12 Quốc gia") + 
  theme (axis.title = element_blank()) #  Cac bieu do da xh theo thu tu ABC

# Làm theo thứ tự các bước sau: 
df_daily_cases  %>% 
  mutate (Country = factor(Country, levels = top12)) -> df_daily_cases1

df_daily_cases1  %>% 
  ggplot(aes(x = Date_confirmation, y = daily_cases, group = Country, color = Country)) + 
  geom_line(show.legend = FALSE, size =1) + 
  facet_wrap(~ Country) +
  labs(title = "Số ca mắc Đậu mùa khỉ ở Top 12 Quốc gia") + 
  theme (axis.title = element_blank()) #  Cac bieu do da xh theo thu tu ABC

Cách 2-Mở rộng cách 1:Cách 1 đã sắp xếp được theo thứ tự, tuy nhiên biểu đồ có lẽ sẽ thể hiện được nhiều thông tin hơn nếu tên biểu đồ “Quốc gia” có đi kèm tổng số ca mắc cộng dồn.

Cách thực hiện như sau:

  • Tạo biến mới bằng stringrfull_join () nối thông tin 2 cột “Quốc gia” + “Số ca”
# Tạo biến mới bằng stringr ĐẾM LUÔN THEO COUNTRY

library(stringr) # Dan bien nay voi bien kia 

monkeypox  %>% 
  filter(Status == "confirmed")  %>% 
  group_by(Country) %>% 
  count(sort = TRUE)  %>% 
  ungroup() %>% 
  slice(1:12) -> n_cases_top12

n_cases_top12 %>% 
  mutate(Country_num = str_c(Country, ": ", n)) -> n_cases_top12_1  # tạo ra biến mới "Country_num với thông tin QG: n"

#-----------------
# 12. full_join ()
#-----------------

full_join(df_daily_cases, n_cases_top12_1, by = "Country") -> df_daily_cases_join

df_daily_cases_join  %>% 
  ggplot(aes(x = Date_confirmation, y = daily_cases, color = Country_num)) +
  geom_line(show.legend = FALSE) +
  facet_wrap( ~ Country) # Tao nhan co so "QG: n" 

n_cases_top12_1  %>% 
  pull(Country_num)  -> top_12_ordered # Tao ra 1 vector moi bao gom "QG: n" 

df_daily_cases_join  %>% 
  mutate(Country_num = factor(Country, levels = top_12_ordered)) %>% 
  ggplot(aes(x = Date_confirmation, y = daily_cases, color = Country)) +
  geom_line(show.legend = FALSE) +
  facet_wrap( ~ Country) # Tạo thêm 1 cột Country_num

# Cách khác: Tạo thêm 1 factor giống "Country_num" 
  
  str_c(top12, ": ", n_cases_top12$n) -> top12_n_cases  # Top 12 FACTOR của các "QG:n" bằng với cột biến "Country_num" 
  
# Sau đó làm tương tự như trên, thêm 1 "facet_wrap" cho biến "Country_num" = tên biểu đồ 
  
  full_join(df_daily_cases, n_cases_top12_1, by = "Country") -> df_daily_cases_join
  
  df_daily_cases_join %>% 
    mutate(Country_num = factor( Country_num, levels = top_12_ordered)) %>% 
    ggplot(aes(x = Date_confirmation, y = daily_cases, color = Country_num)) +
    geom_line(show.legend = FALSE) +
   facet_wrap (~ Country_num)

   facet_wrap( ~ Country)
## <ggproto object: Class FacetWrap, Facet, gg>
##     compute_layout: function
##     draw_back: function
##     draw_front: function
##     draw_labels: function
##     draw_panels: function
##     finish_data: function
##     init_scales: function
##     map_data: function
##     params: list
##     setup_data: function
##     setup_params: function
##     shrink: TRUE
##     train_scales: function
##     vars: function
##     super:  <ggproto object: Class FacetWrap, Facet, gg>

Cách 3: Tương tự cách 2

# Cach 3
 monkeypox %>% 
  filter(Status == "confirmed") %>% 
  group_by(Country)  %>% 
  count(sort = TRUE) %>%  
  ungroup ()  %>% 
  slice(1:12)  %>% 
  pull(Country) -> top12 
 
 monkeypox %>% 
  filter(Status == "confirmed") %>% 
  filter(Country %in% top12)  %>% 
  group_by(Country, Date_confirmation) %>% 
  summarise(daily_cases = n()) %>% 
    ungroup() -> df_daily_cases
 
monkeypox  %>% 
  filter(Status == "confirmed")  %>% 
  group_by(Country) %>% 
  count(sort = TRUE)  %>% 
  ungroup() %>% 
  slice(1:12)  %>% 
  mutate(Country_num1 = str_c(Country, ": ", n)) -> n_cases_top12_2


full_join(df_daily_cases, n_cases_top12_2, by = "Country") -> df_daily_cases2
  
 
 str_c(top12, ": ", n_cases_top12$n) -> top12_new
  
 
df_daily_cases2  %>% 
    mutate(Country_num1 = factor( Country_num1, levels = top12_new)) %>% 
    ggplot(aes(x = Date_confirmation, y = daily_cases, color = Country_num1)) +
    geom_line(show.legend = FALSE) +
   facet_wrap (~ Country_num1)

   facet_wrap( ~ Country)
## <ggproto object: Class FacetWrap, Facet, gg>
##     compute_layout: function
##     draw_back: function
##     draw_front: function
##     draw_labels: function
##     draw_panels: function
##     finish_data: function
##     init_scales: function
##     map_data: function
##     params: list
##     setup_data: function
##     setup_params: function
##     shrink: TRUE
##     train_scales: function
##     vars: function
##     super:  <ggproto object: Class FacetWrap, Facet, gg>

2.3. Vẽ bản đồ thế giới về phân bố bệnh Đậu mùa khỉ (Monkeypox map)

2.3.1. Kiểm tra thông tin sơ bộ và fix trước khi join dữ liệu

Cần cài đặt package “maps”, “unique”, “setdiff”,

Tạo ra bảng 2 biến: Quốc gia và tổng số ca mắc tích luỹ

# Calculate confirmed cases by country: 

monkeypox  %>% 
  filter(Status == "confirmed") %>% 
  group_by(Country) %>% 
  count(sort = TRUE) %>% 
  ungroup() -> total_cases_nation # Tạo ra bảng 2 biến: Quốc gia và tổng số ca mắc tích luỹ 

Load dữ liệu không gian “hành chính” của bản đồ thế giới

# load geom-spatial data: 
df_world <- map_data("world")

Kiểm tra sự khác biệt về mã hoá code tên Quốc gia / states bằng lệnh unique

Dưới đây là ví dụ để giải thích thêm về lệnh unique –> tìm ra sự duy nhất trong chuỗi thông tin của 1 biến (thông tin bị trùng nhau chỉ tính 1 lần)

# Lệnh "unique": giai thich 
 x <-  c("dung", "binh", "na", "dung")
 unique(x)
## [1] "dung" "binh" "na"

Kiểm tra sự khác biệt về tên Quốc gia trong 2 bộ dữ liệu để matching lại khớp nhau trước khi join

# Check differences: 
nations_from_monkey <- total_cases_nation$Country # tạo tên QG từ dữ liệu ĐMK 

df_world  %>% 
  pull(region) %>% 
  unique() -> nations_world # Tạo tên QG từ dữ liệu hành chính TG 

setdiff(nations_from_monkey, nations_world)
## [1] "United States"                    "England"                         
## [3] "Democratic Republic Of The Congo" "Scotland"                        
## [5] "Wales"                            "Northern Ireland"                
## [7] "Gibraltar"                        "Bosnia And Herzegovina"

Kết quả cho thấy có 8 sự khác biệt trong các tên Quốc gia: Ví dụ ở bộ ĐMK thì ghi là “United States” - trong khi bộ dữ liệu hành chính TG thì ghi là “USA”

Việc tiếp theo cần làm là “matching” lại cho khớp, cần sử dụng package “stringr”str_detect

Giải thích về lệnh “setdiff”

# Giai thich ve lenh "setdiff" 
a <- c("thailand", "laos", "Viet nam", "us")
b <- c("thailand", "Vietnam", "united states", "laos")
setdiff(a,b)
## [1] "Viet nam" "us"
# Muon join lai thi chi can doi 1 trong 2
case_when(b == "Viet nam" ~ "Vietnam",
          b == "us" ~ "united states",
          TRUE ~ a)
## [1] "thailand" "laos"     "Viet nam" "us"
# 
case_when(a == "Viet nam" ~ "Vietnam",
          a == "us" ~ "united states",
          TRUE ~ a) -> c 

setdiff(c,b) # da fix hoan toan = 0 khac biet 
## character(0)

Giải thích về lệnh “str_detect”

# Giai thich Lenh "str_detect":  truy cap vao vector theo tung vi tri HOAC logic (True/false)
x <-  c("dung", "binh", "na", "dung")

str_detect(x, "ng")
## [1]  TRUE FALSE FALSE  TRUE
# Lay ra cac doi tuong co chua "ng" 
x[str_detect(x, "ng")] 
## [1] "dung" "dung"

Kiểm tra sự khác biệt giữa 8 biến khác biệt bên trên:

# Load stringr package: 
library(stringr)

# 1. United States: 
nations_world[str_detect(nations_world, "United States")] # 0 chứa tên này --> vào xem nó là tên gì: USA 
## character(0)
nations_from_monkey[str_detect(nations_from_monkey, "United States")] # có chứa tên này 
## [1] "United States"
# 2. England
nations_world[str_detect(nations_world, "England")]  # 0 chua ten nay --> Vao xem no la gi: UK --> subgroup 
## character(0)
df_world  %>% 
  filter(region == "UK") %>% 
  group_by(subregion, group)  %>% 
  ungroup() -> UK 

UK  %>% 
  group_by(subregion) %>% 
  count()
## # A tibble: 5 × 2
## # Groups:   subregion [5]
##   subregion            n
##   <chr>            <int>
## 1 Great Britain      512
## 2 Isle of Wight       13
## 3 Northern Ireland    99
## 4 Scotland           352
## 5 Wales               14
# Kết quả cho ra có 5 QG nhỏ trong UK gồm: Great Britain, Isle of Wight, Northern Ireland, Scotland, Wales 
# LƯU Ý: Great Britain theo địa lý gồm 3 QG: England, Scotland, Wales - TUY NHIÊN bản đồ TG hàm chỉ Great Britain = England 
nations_from_monkey [str_detect(nations_from_monkey, "England")] # KQ cho ra 1 KQ "England" --> Chỉ cần mã hoá cho "Great Britain" thành "England"  
## [1] "England"
# 3,4,5. Scotland; Wales, và Northern Ireland: Đáng lưu ý 
# 3. Scotland
nations_world[str_detect(nations_world, "Scotland")]  # 0 chua ten nay vì trong region nó thuộc UK--> Nó là Scotland ở trong subregion 
## character(0)
nations_from_monkey [str_detect(nations_from_monkey, "Scotland")] # Chính là nó 
## [1] "Scotland"
# --> Phải matching làm sao Scotland ở trong data ĐMK khớp với trong Subregion của bộ dữ liệu TG 


# 4. Wales
nations_world[str_detect(nations_world, "Wales")]  # 0 chua ten nay vì trong region nó thuộc UK--> Nó là Wales ở trong subregion 
## character(0)
nations_from_monkey [str_detect(nations_from_monkey, "Wales")] # Chính là nó --> Phải matching làm sao Wales ở trong data ĐMK khớp với trong Subregion của bộ dữ liệu TG 
## [1] "Wales"
# 5. Northern Ireland
nations_world[str_detect(nations_world, "Northern Ireland")]  # 0 chua ten nay vì trong region nó thuộc UK--> Nó là Northern Ireland ở trong subregion 
## character(0)
nations_from_monkey [str_detect(nations_from_monkey, "Northern Ireland")] # Chính là nó --> Phải matching làm sao Northern Ireland ở trong data ĐMK khớp với trong Subregion của bộ dữ liệu TG 
## [1] "Northern Ireland"
# 6. Democratic Republic Of The Congo 
nations_world[str_detect(nations_world, "Democratic Republic Of The Congo")]  # 0 chua ten nay --> Vao xem no la gi: Democratic Republic of the Congo
## character(0)
nations_from_monkey [str_detect(nations_from_monkey, "Democratic Republic Of The Congo")] # KQ cho ra chính nó 
## [1] "Democratic Republic Of The Congo"
# LƯU Ý: "Ireland" đã khớp nhau: nó đúng ra là Republic of Ireland; cùng với Northern Ireland hợp thành "Ireland", ở đây được viết tắt lại 

# 7. Gibraltar: có 5 ca 
nations_world[str_detect(nations_world, "Gibraltar")]  # 0 chua ten nay --> Vao xem no la gi: --> Không tìm thấy --> search gg thấy gần lãnh thổ "Spain" 
## character(0)
nations_from_monkey [str_detect(nations_from_monkey, "Gibraltar")] # KQ cho ra chính nó --> Gán nó vào với Spain 
## [1] "Gibraltar"
# 8. Bosnia And Herzegovina 

nations_world[str_detect(nations_world, "Bosnia And Herzegovina")]  # 0 chua ten nay --> Vao xem no la gi: "Bosnia and Herzegovina" 
## character(0)
nations_from_monkey [str_detect(nations_from_monkey, "Bosnia And Herzegovina")] # Chính là nó --> gán lại cho khớp 
## [1] "Bosnia And Herzegovina"

Thực hiện gán lại các biến cho khớp:

Thực hiện matching 3 QG ở biến “region” trước: số 1, 6, 8.

df_world %>% 
  mutate(region = case_when(region == "USA" ~ "United States",
                            region == "Democratic Republic of the Congo" ~ "Democratic Republic Of The Congo",
                            region == "Bosnia and Herzegovina" ~ "Bosnia And Herzegovina",
                            TRUE ~ region)) -> df_world_matching1

# Check differences again: 

setdiff(nations_from_monkey, df_world_matching1$region %>% unique())
## [1] "England"          "Scotland"         "Wales"            "Northern Ireland"
## [5] "Gibraltar"

Thực hiện matching ở 5 QG phức tạp hơn (phân bổ trong subregion) như sau:

Đầu tiên thực hiện matching 3 QG thuộc UK: Scotland; Wales, và Northern Ireland:

# Scotland; Wales, và Northern Ireland:
  
df_world_matching1  %>% mutate(region_new = case_when(
  region == "UK" ~ subregion, 
  TRUE ~ region)) -> df_world_matching1_new

setdiff(nations_from_monkey, df_world_matching1_new$region_new %>% unique())
## [1] "England"   "Gibraltar"

Kết quả cho thấy còn 2 sự khác biệt: “England” và “Gibraltar”

Đổi mục 2. “England”

df_world_matching1_new %>% 
  mutate(region_new1 = case_when(
  region_new == "Great Britain" ~ "England", 
  TRUE ~ region_new)) -> df_world_matching1_new1
setdiff(nations_from_monkey, df_world_matching1_new1$region_new1 %>% unique())
## [1] "Gibraltar"

Kết quả cho thấy chỉ còn 1 sự khác biệt: “Gibratar” –> Cần đổi ở bộ dataframe “total_cases_nation”

Cuối cùng đổi mục còn lại số 7. Gibraltar

# Đổi QG số 7. Gibraltar 

total_cases_nation   %>% 
  mutate(country_new = case_when(
    Country == "Gibraltar" ~ "Spain",
    TRUE ~ Country)) -> total_cases_nation_new

nations_from_monkey_new <- total_cases_nation_new$country_new

setdiff(nations_from_monkey_new, df_world_matching1_new1$region_new1 %>% unique())
## character(0)

Kết quả cho thấy đã matching được hết. Yay! Well done! :)

2.3.2. Giải thích sơ bộ về mapping qua vẽ 1 hình tam giác qua 3 điểm (tam giác)

# Giải thích sơ bộ về mapping
data.frame(diem = c("a", "b", "c"),
           x = 0:2,
           y = c(0,2,1)) -> df_tamgiac

df_tamgiac  %>% 
  ggplot(aes(x = x, y =y)) +
  geom_polygon()

# Trang tri them cho tam giac
df_tamgiac  %>% 
  ggplot(aes(x = x, y =y)) +
  geom_polygon(fill = "red", color = "red", size = 1, alpha = 0.2)

2.3.3. Thực hiện vẽ bản đồ thế giới “hành chính”

# Ve ban do TG 
df_world  %>% 
  ggplot(aes(long, lat, group = group)) +
  geom_polygon()

# Tao them duong vien o ngoai QG
df_world  %>% 
  ggplot(aes(long, lat, group = group)) +
  geom_polygon() +
  geom_path(color = "red")

# khong muon su dung du lieu cua "Chau Nam Cuc" --> lat >= -55
df_world  %>% 
  filter( lat >= -55)  %>% 
  ggplot(aes(long, lat, group = group)) +
  geom_polygon() +
  geom_path(color = "red")

2.3.4. Thực hiện vẽ bản đồ thế giới “Monkeypox”

# Join the two data sets: 

full_join(df_world_matching1_new1, total_cases_nation_new, by = c("region_new1" = "country_new")) -> world_monkeypox

# Co the co cach khac: Doi ten "region_new1" thanh "Country_new" hoac nguoc lai 

# A draft of monkeypox map: 

world_monkeypox  %>% 
  ggplot(aes(long, lat, group = group, fill = n)) +
  geom_polygon(color = "white", size = 0.02)

# Cach khac
world_monkeypox  %>% 
  filter (lat >= -55)  %>% 
  ggplot(aes(x = long, y = lat, group = group, fill = n)) +
  geom_polygon(color = "white", size = 0.02)

2.4. Vẽ biểu đồ đẹp hơn

Đọc thêm tại đây về cách vẽ bản đồ đẹp hơn với ggplot2

Sử dụng package “viridis” và mã màu “#f5f5f2”

# Make the draft more elegant
library(viridis)

bgr_color <- "#f5f5f2"

2.4.1. Cách 1:

# Option 1: 

world_monkeypox  %>% 
  filter(lat >= - 55)  %>% 
  ggplot(aes(long, lat, group = group, fill = n)) +
  geom_polygon(color = "white", size = 0.02) + 
  theme_minimal() +
  theme(legend.position = "top", legend.direction = "horizontal") +
  scale_fill_viridis(direction = -1,
                     option = "D",
                     name = "Monkeypox Density", 
                     guide = guide_colorbar(direction = "horizontal",
                                            barheight = unit(3, units = "mm"),
                                            barwidth = unit(40, units = "mm"),
                                            title.hjust = 05,
                                            label.hjust = 0.5,
                                            discrete = TRUE,
                                            reverse = TRUE,
                                            title.position = "top")) +
  theme(axis.title = element_blank()) +
  theme(axis.text = element_blank()) +
  theme(panel.grid = element_blank())+
  theme(plot.background = element_rect(fill = bgr_color, color = NA))

2.4.2. Cách 2:

# Option 2: 

world_monkeypox  %>% 
  filter(lat >= -55)  %>% 
  ggplot(aes(long, lat, group = group, fill = n)) +
  geom_polygon(color = "white", size = 0.02) +
  theme_minimal() +
  theme(legend.position = "top", legend.direction = "horizontal") +
  scale_fill_viridis(direction = -1,
                     option = "C",
                     name = "Global Monkeypox Density",
                     guide = guide_colorbar(direction = "horizontal",
                                            barheight = unit(3, units = "mm"),
                                            barwidth = unit(40, units = "mm"),
                                            title.hjust = 0.5,
                                            label.hjust = 0.5,
                                            discrete = TRUE,
                                            reverse = TRUE,
                                            title.position = "top")) +
  theme(axis.title = element_blank()) +
  theme(axis.text = element_blank()) +
  theme(panel.grid = element_blank()) +
  theme(plot.background = element_rect(fill = "black", color = NA)) +
  theme(legend.text = element_text(color = "white")) +
  theme(legend.title = element_text(color = "white")) +
  labs(title = "Geographical distribution of confirmed cases of MPX, \n as of 01 Aug 2022",
       caption = "Source: https://github.com/globaldothealth/monkeypox") +
  theme(plot.title = element_text(color = "white", size = 16)) +
  theme(plot.caption = element_text(color = "white", size = 8, face = "italic"))

2.5. Chuyển đổi dữ liệu ngang-dọc trong data frame

Đọc thêm tại Converting data between wide and long format

2.5.1. Ví dụ về Long form

Để tìm hiểu kỹ hơn tham khảo thêm tại tài liệu này

Bộ dữ liệu iris đình đám (“Hoa diên vĩ”) search gg tự đọc thêm

rm(list = ls())

#  Data form: Convert Long to wide (and Vice Versa)
# Ví dụ về long form / An example of long form: 
# VD1: 
?iris # Bộ dữ liệu iris đình đám ("Hoa diên vĩ") search gg tự đọc thêm 

# Dem xem co bao nhieu loai trong Species 
# Cach 1: 
iris  %>%  head()
##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1          5.1         3.5          1.4         0.2  setosa
## 2          4.9         3.0          1.4         0.2  setosa
## 3          4.7         3.2          1.3         0.2  setosa
## 4          4.6         3.1          1.5         0.2  setosa
## 5          5.0         3.6          1.4         0.2  setosa
## 6          5.4         3.9          1.7         0.4  setosa
count(iris, iris$Species)
##   iris$Species  n
## 1       setosa 50
## 2   versicolor 50
## 3    virginica 50
# Cach 2:  
iris$Species  %>%  unique()
## [1] setosa     versicolor virginica 
## Levels: setosa versicolor virginica
iris  %>% 
group_by( Species)  %>% 
  count()
## # A tibble: 3 × 2
## # Groups:   Species [3]
##   Species        n
##   <fct>      <int>
## 1 setosa        50
## 2 versicolor    50
## 3 virginica     50
iris  %>% 
group_by( Species)  %>% 
  summarise(trung_binh = mean( Sepal.Length),
            MAX = max(Sepal.Length), 
            MIN = min(Sepal.Length), 
            SD = sd(Sepal.Length),
            n_obs = n ())
## # A tibble: 3 × 6
##   Species    trung_binh   MAX   MIN    SD n_obs
##   <fct>           <dbl> <dbl> <dbl> <dbl> <int>
## 1 setosa           5.01   5.8   4.3 0.352    50
## 2 versicolor       5.94   7     4.9 0.516    50
## 3 virginica        6.59   7.9   4.9 0.636    50

2.5.2. Thực hành trên bộ data MONKEYPOX

readr::read_csv("https://raw.githubusercontent.com/globaldothealth/monkeypox/main/latest.csv") -> monkeypox


monkeypox  %>% 
  filter(!is.na(Gender)) %>% 
  mutate(Gender = case_when(Gender == "male" ~ "Male",
                            Gender == "female" ~ "Female",
                            TRUE ~ Gender))  %>% 
  group_by(Status, Gender) %>% 
  summarise(freq = n()) %>% 
  ungroup() -> long_form_data

Hình ảnh hoá long form trên biểu đồ

# With long form data: 
long_form_data %>% 
  ggplot(aes(y = Status, x = freq, fill = Gender)) +
  geom_col(position = "dodge")

long_form_data  %>% 
  ggplot(aes(y = Status, x = freq, fill = Gender)) +
  geom_col(position = "stack")

long_form_data %>% 
  ggplot(aes(y = Status, x = freq, fill = Gender)) + 
  geom_col(position = "fill")

2.5.3. Chuyển đổi từ long sang wide form

Sử dụng package “tidyr” –> pivot_wider

# Convert long to wide: 
library(tidyr)

# a. Biến theo giới tính 

long_form_data %>% 
  pivot_wider(names_from = "Gender", 
              values_from = "freq") -> df_wide1

# b. Biến theo chẩn đoán 
long_form_data  %>% 
  pivot_wider(names_from = "Status", 
              values_from = "freq") -> df_wide2

2.5.4. Chuyển đổi từ wide sang long form

Sử dụng pivot_longer

df_wide1  %>% 
  pivot_longer(cols = c("Male", "Female"), 
               names_to = "gioi_tinh", 
               values_to = "tan_suat") -> df_long1 

2.5.5. Áp dụng vào 1 số tình huống chuyển đổi

a. Ví dụ về “economics”

#  An application of data form transformation
# Load economics data set: 
?economics

data("economics")

#
economics  %>% 
  ggplot(aes( x = date, y = psavert)) +  
          geom_line() +
          labs (title = "Tiet kiem ca nhan") -> p1
economics  %>% 
  ggplot(aes(x = date, y = unemploy)) +
  geom_line() +
  labs(title = "That nghiep") -> p2

library(gridExtra)

grid.arrange(p1, p2) # Mac dinh thi p1 xuat hien truoc, p2 Xuat hien sau 

grid.arrange(p1, p2, ncol = 2) # De 2 cot song song nhau 

# Note: Lenh Grid co ve "tay chan" nhung co loi o cho la cac bieu do khac nhau: "line/bar/pie charts" 


# Convert to long form: 

economics  %>% 
  pivot_longer(cols = c("pce", "pop", "psavert", "uempmed", "unemploy"),
               names_to = "chi_so",
               values_to = "value") -> econ_long 

# Application of long form: 

econ_long %>% 
  ggplot(aes(x = date, y = value, color = chi_so)) + 
  geom_line() + 
  facet_wrap(~ chi_so)

# Khac nhau ve scale --> can de scale "free" 
econ_long %>% 
  ggplot(aes(x = date, y = value, color = chi_so)) + 
  geom_line() + 
  facet_wrap(~ chi_so, scales = "free")

# Convert to wide form: 

econ_long %>% 
  pivot_wider(names_from = "chi_so", 
              values_from = "value") -> to_wide_form

b. Ví dụ về Ebola

Nguồn dữ liệu Ebola

# Application of long form with Ebola data from
readxl::read_excel("~/Documents/8. R skills/R_epirhandbook/R_epirhandbook_data/linelist_raw.xlsx") -> ebola_data

ebola_data  %>% 
  select(outcome, fever, gender)  %>% 
  filter(!is.na(outcome), !is.na(fever), !is.na(gender)) %>% 
  group_by(outcome, fever, gender)  %>% 
  count() %>% 
  ungroup() -> df_for_ploting

df_for_ploting  %>% 
  ggplot(aes(y = outcome, x = n, fill= gender)) +
  geom_col(position =  "fill") +
  facet_wrap( ~ fever)

df_for_ploting  %>% 
  ggplot(aes(y = outcome, x = n, fill= gender)) +
  geom_col(position =  "stack") +
  facet_wrap( ~ fever)

df_for_ploting  %>% 
  ggplot(aes(y = outcome, x = n, fill= gender)) +
  geom_col(position =  "dodge") +
  facet_wrap( ~ fever)

Cảm ơn Thầy Dũng rất nhiều! Bài học vô cùng hữu ích, cần luyện tập nhiều lần để thấm :D

Cảm ơn cả nhà đã đọc tới đây.

Best wishes,

Bảo Huyền.