application <- read.csv("data/application_sample.csv")
FPT <- read.csv("data/FPT.csv")
MWG <- read.csv("data/MWG.csv")
VNM <- read.csv("data/VNM.csv")
head(application)
head(FPT)

1. Package ggplot2

aes()

1.1. Scatter Plot

library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(ggplot2)
mutate(application, 
       AMT_INCOME_TOTAL = log(AMT_INCOME_TOTAL),
       AMT_CREDIT = log(AMT_CREDIT)) %>% 
  ggplot(aes(x = AMT_INCOME_TOTAL, y = AMT_CREDIT)) +
    geom_point(
      col = "#909090", 
      size = 2,
      alpha = 0.5
    ) +
    geom_smooth(
      method = "lm", 
      se = F,
      colour = 'red',
      linewidth = 1.2
    )
## `geom_smooth()` using formula = 'y ~ x'


Vẽ màu theo nhóm

application1 <- application %>% 
  mutate(log_income  = log(AMT_INCOME_TOTAL),
         log_credit = log(AMT_CREDIT))
scatter1 <- ggplot(application1, aes(log_income, log_credit)) +
  geom_point(aes(col = CODE_GENDER)) +
  geom_smooth(
    method = "lm", 
    # formula = "y ~ x + I(x^2)",
    se = F, 
    aes(col = CODE_GENDER)
  ) +
  labs(
    x = "INCOME", # đổi tên trục x 
    y = "CREDIT", # đổi tên trục y
    title = "Tương quan giữa INCOME và CREDIT",
    col = "Giới tính" # đặt tên legend
  ) +
  theme_bw(base_size = 12) # thay đổi chủ đề biểu đồ
scatter1 + 
  theme( # tinh chỉnh mọi thứ với biểu đồ
    plot.title = element_text(
      face = "bold", # in đậm
      hjust = 0.5, # căn dòng
      margin = margin(b = 12), # tăng khoảng cách bên dưới
      size = 13 # thay đổi kích thước text
    ),
    axis.title.x = element_text(margin = margin(t = 13), size = 12),
    axis.title.y = element_text(margin = margin(r = 13), size = 12),
    legend.position = "bottom" # "left", "right", "bottom", "top"
  )
## `geom_smooth()` using formula = 'y ~ x'


1.2. Histogram

Thực hiện:

  • Đổi màu

  • Đổi tên các trục, đổi tên biểu đồ

  • Đổi theme

application1 %>% mutate(
  CODE_GENDER = case_when(
    CODE_GENDER == 'F' ~ 'Nữ',
    CODE_GENDER == 'M' ~ 'Nam'
  )
) %>% 
  ggplot(aes(x = log_income)) +
    geom_histogram(
      aes(fill = CODE_GENDER),
      col = "white", 
      bins = 50
    ) +
    labs(
      title = "Biểu đồ phân bố thu nhập",
      x = "Thu nhập",
      y = "Tần số",
      fill = "Giới tính"
    ) +
    theme_bw() +
    scale_fill_manual(
      values = c('Nữ'='#999999', 'Nam'='#eeeeee')
    )


1.3. Biểu đồ tròn (pie)

Tỷ lệ nam nữ

group_by(application1, CODE_GENDER) %>% 
  summarise(count = n()) %>% 
  ggplot(aes(x = "", y = count, fill = CODE_GENDER)) +
    geom_col() +
    coord_polar(theta = 'y') +
    geom_text(
      aes(
        label = 
            paste0(count/nrow(application1) * 100, '%')
      ),
      position = position_stack(vjust = 0.5)
    ) +
    theme_void() + # bỏ phần thừa
    labs(
      fill = "Giới tính"
    )


1.4. Boxplot

ggplot(application1, aes(log_income)) +
  geom_boxplot(aes(fill = CODE_GENDER))

# r base
hist(
  application1$log_income, 
  col = 'steelblue', 
  border = 'white',
  main = "Kết hợp histogram và boxplot",
  xlab = "Income"
)
par(new = TRUE)
boxplot(
  application1$log_income, 
  axes = FALSE,
  horizontal = TRUE,
  col = rgb(1, 0, 0, 0.5)
)


1.5. Biểu đồ đường

FPT <- FPT %>% 
  select(date, open, high, low, close, match.volume)
# lưu ý: trục phải ở dạng date
mutate(FPT, date = as.Date(date)) %>% 
  ggplot(aes(date, close)) +
    geom_line(col = 'steelblue') + 
    geom_smooth() +
    theme_bw()
## `geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'


Time series trong 1 năm (dữ liệu theo ngày), hiển thị trên trục x là các quý trong năm 2022

Trường hợp này cần sử dụng hàm scale_x_date với thông số:

  • date_breaks: truyền vào character cho khoảng cách thời gian bất kì với đơn vị là month, year, …

  • date_minor_breaks: truyền vào giá trị tương tự như date_breaks, chỉ định khoảng cách hiển thị giữa 2 phần tick với nhau

  • labels format labels và cần truyền vào function để format

    • tạo function nhận x là tham số đầu vào và dùng as.yearqtr để chuyển thành dạng quý
library(zoo) # dùng hàm as.yearqtr
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
mutate(FPT, date = as.Date(date)) %>% 
  filter(date >= '2022-01-01' & date <= '2022-12-31') %>%
  ggplot(aes(date, close)) +
    geom_line() +
    scale_x_date(
      date_breaks = '3 months', # quý
      date_minor_breaks = '1 month',
      labels = function(x) {
        as.yearqtr(x)
      }
    )


2. Hàm (function)

my_func <- function(a, b) {
  return(a + b)
}
my_func(10, 5)
## [1] 15


Tạo hàm vẽ histogram, được format sẵn

application <- application %>% 
  mutate(
    AMT_INCOME_TOTAL = log(AMT_INCOME_TOTAL),
    AMT_CREDIT = log(AMT_CREDIT),
  )
myHist <- function(data, x, cate, xlab, ylab, fillLab) {
  p <- ggplot(data, aes({{x}})) + 
    geom_histogram(aes(fill = {{cate}})) +
    theme_bw() +
    labs(
      x = xlab,
      y = ylab,
      fill = fillLab
    )
  return(p)
}
myHist(application, 
       AMT_CREDIT, 
       NAME_CONTRACT_TYPE, 
       'Thu nhập',
       'Tần số',
       'Loại hợp đồng')
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

myHist(application, 
       AMT_CREDIT, 
       CODE_GENDER, 
       'Credit',
       'Tần số',
       'Giới tính')
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.