Data Visualization

tmt

2024-03-05

Đọc dữ liệu từ file csv

d <- read.csv(file.choose(), header = T)
read.csv(file = './data/abc.csv')

Đọc dữ liệu từ file Excel

  • Cài đặt và load gói xlsx
install.packages('xlsx')
library(xlsx)
  • Đọc dữ liệu từ file
tmp <- read.xlsx(file.choose(), sheetIndex = 1, header = T)
tmp <- read.xlsx(file = './data/abc.xlsx')

Sử dụng dữ liệu có sẵn trong R

  1. Load package và load datasets
library(datasets)
data(package = 'datasets')

library(ggplot2)
data(package = 'ggplot2')
  1. Gán dữ liệu cho 1 đối tượng để làm việc
tmp <- swiss
tmp <- diamonds
tmp <- read.csv("https://data.nber.org/cps-basic2/csv/cpsb202302.csv")

Lấy dữ liệu từ World Bank

Cơ sở dữ liệu của WB lưu trữ rất thông tin về rất nhiều lĩnh vực khác nhau của thế giới, từ dữ liệu kinh tế, xã hội, môi trường cho đến tài chính,… của nhiều nước trên thế giới.

library(WDI)
ind <- WDIsearch('Total reserves')
d <- WDI(indicator = 'FI.RES.TOTL.MO', country = c('VNM'), extra = T)
tmp <- d %>% select(year,FI.RES.TOTL.MO)
tmp <- na.omit(tmp)
names(tmp) <- c('year','DuTru')

Tài liệu tham khảo

  • https://rkabacoff.github.io/datavis/
  • https://psu-psychology.github.io/r-bootcamp-2019/talks/ggplot_grammar.html

Bộ dữ liệu diamonds - Bar chart

Đây là bộ dữ liệu có sẵn trong package ggplot2.

library(tidyverse)
library(scales)
tmp <- diamonds
tmp %>% ggplot(aes(x = cut)) +
    geom_bar() +
    labs(x = 'Loại', y = 'Số lượng')

Bộ dữ liệu diamonds - Bar chart

tmp <- diamonds
tmp %>% ggplot(aes(x = cut)) +
    geom_bar() +
    labs(x = 'Loại', y = 'Số lượng') +
    coord_flip()

Bộ dữ liệu diamonds - Bar chart (tt)

tmp %>% group_by(cut) %>% summarise(n = n()) %>%
  ggplot(aes(cut,n)) +
    geom_col(fill='green') +
    geom_text(aes(label = n),vjust = 2, color = 'red') +
    labs(x = 'Loại', y = 'Số lượng')

Bộ dữ liệu diamonds - Bar chart (tt)

tmp %>% group_by(cut) %>% summarise(n = n()) %>%
  ggplot(aes(cut,n)) +
    geom_col(fill='green') +
    geom_text(aes(label = percent(n/length(tmp$carat))),vjust = 2, color = 'red') +
    labs(x = 'Loại', y = 'Số lượng')

Bộ dữ liệu diamonds - Bar chart (tt)

tmp %>% group_by(cut,color) %>% summarise(n=n()) %>%
  ggplot(aes(x = cut,y = n)) +
    geom_col(position = 'dodge') +
    facet_wrap(~color) +
    labs(x = 'Loại', y = 'Số lượng')

Bộ dữ liệu diamonds - Bar chart (tt)

tmp %>% group_by(cut,color) %>% summarise(n=n()) %>%
  ggplot(aes(x = cut,y = n)) +
    geom_col(position = 'dodge') +
    facet_wrap(~color) +
    geom_text(aes(label = n),vjust = 2, color = 'green') +
    labs(x = 'Loại', y = 'Số lượng')

Bộ dữ liệu diamonds - Bar chart (tt)

tmp <- diamonds
tmp %>% group_by(cut) %>% summarise(m= mean(carat)) %>%
  ggplot(aes(x = cut,y = m)) +
    geom_col(position = 'dodge') +
    geom_text(aes(label = round(m,2)), vjust = 2, color = 'green') +
    labs(x = 'Màu', y = 'Mean')

Bộ dữ liệu diamonds - Bar chart (tt)

tmp <- diamonds
tmp %>% group_by(cut,color) %>% summarise(m = mean(price)) %>%
  ggplot(aes(x = cut,y = m)) +
    geom_col(position = 'dodge') +
    facet_wrap(~color) +
    geom_text(aes(label = round(m))) +
    labs(x = 'cut', y = 'Số lượng')

Bộ dữ liệu diamonds - Bar chart (tt)

tmp <- diamonds
tmp <- tmp %>% group_by(cut, color) %>% summarise(n = n())
tmp %>% ggplot(aes(x = cut, y = n)) +
  geom_col(data = tmp %>% filter(color == 'D'), fill = 'red') +
  geom_col(data = tmp %>% filter(color == 'J'), fill = 'blue')

Bộ dữ liệu diamonds - Bar chart (tt)

tmp <- diamonds 
tmp <- tmp %>% mutate(caratC = cut(carat,5, label = c('rất nhỏ', 'nhỏ','vừa','lớn','rất lớn')))
tmp %>% ggplot(aes(x = caratC)) +
  geom_bar(fill = 'red')

Bộ dữ liệu diamonds - Histogram

tmp <- diamonds
tmp %>% ggplot(aes(x = price)) +
  geom_histogram(binwidth = 500, fill = 'blue', color = 'red')

Bộ dữ liệu diamonds - Histogram (tt)

tmp <- diamonds
tmp %>% ggplot(aes(x = price, fill = color)) +
  geom_histogram(binwidth = 500)

Bộ dữ liệu diamonds - Histogram (tt)

tmp <- diamonds
tmp %>% ggplot(aes(x = price)) +
  geom_histogram(binwidth = 500, fill = 'blue', color = 'red') +
  facet_wrap(~color)

Bộ dữ liệu diamonds - Histogram (tt)

tmp <- diamonds
tmp %>% ggplot(aes(x = price)) +
  geom_histogram(data = tmp %>% filter(color == 'G'), binwidth = 500, fill = 'red') +
  geom_histogram(data = tmp %>% filter(color == 'J'), binwidth = 500, fill = 'green')

Bộ dữ liệu diamonds - density

tmp <- diamonds
tmp %>% ggplot(aes(x = price)) +
  geom_density(fill = 'red')

Bộ dữ liệu diamonds - density (tt)

tmp <- diamonds
tmp %>% ggplot(aes(x = price, fill = cut)) +
  geom_density()

Bộ dữ liệu diamonds - density (tt)

tmp <- diamonds
tmp %>% ggplot(aes(x = price)) +
  geom_density(fill = 'green') +
  facet_wrap(~cut)

Bộ dữ liệu diamonds - Pie chart (tt)

tmp <- diamonds
tmp %>% group_by(color) %>% summarise(n = n()) %>%
  ggplot(aes(x = '', y = n,fill = color)) +
    geom_col() +
    geom_text(aes(label = n),position = position_stack(vjust = 1))

Bộ dữ liệu diamonds - Pie chart (tt)

tmp <- diamonds
tmp %>% group_by(color) %>% summarise(n = n()) %>%
  ggplot(aes(x = '', y = n,fill = color)) +
    geom_col() +
    coord_polar('y')

Bộ dữ liệu diamonds - Pie chart (tt)

tmp <- diamonds
tmp %>% group_by(color) %>% summarise(n = n()) %>%
  ggplot(aes(x = '', y = n,fill = color)) +
    geom_col(color = 'black') +
    coord_polar('y') +
    geom_text(aes(x = 1.3, label = n),position = position_stack(vjust = .5)) +
    theme_void()

Bộ dữ liệu diamonds - Pie chart (tt)

tmp <- diamonds
tmp <- tmp %>% filter(cut == 'Good' )
tmp %>% group_by(color) %>% summarise(n = n()) %>%
  ggplot(aes(x = '', y = n,fill = color)) +
    geom_col(color = 'black', width = 1) +
    coord_polar('y') +
    geom_text(aes(x = 1.3, label = n),position = position_stack(vjust = .5)) +
    theme_void()

Bộ dữ liệu iris - scatter

tmp <- iris
tmp %>% ggplot(aes(x = Sepal.Length, y = Petal.Length)) +
  geom_point() +
  xlab('Độ dài đài hoa') + 
  ylab('Độ dài của cánh hoa')

Bộ dữ liệu iris - scatter (tt)

tmp <- iris
tmp %>% ggplot(aes(x = Sepal.Length, y = Petal.Length, color = Species)) +
  geom_point()

Bộ dữ liệu iris - scatter (tt)

tmp <- iris
tmp %>% ggplot(aes(x = Sepal.Length, y = Petal.Length, shape = Species)) +
  geom_point()

Bộ dữ liệu iris - scatter (tt)

tmp <- iris
tmp %>% ggplot(aes(x = Sepal.Length, y = Petal.Length, size = Species)) +
  geom_point()

Bộ dữ liệu iris - scatter (tt)

tmp <- iris
tmp %>% ggplot(aes(x = Sepal.Length, y = Petal.Length, alpha = Species)) +
  geom_point()

Bộ dữ liệu iris - scatter (tt)

tmp <- iris
tmp %>% ggplot(aes(x = Sepal.Length, y = Petal.Length)) +
  geom_point(color = 'red') +
  geom_smooth(method = 'lm', color = 'green')

Bộ dữ liệu iris - scatter (tt)

tmp <- iris
tmp %>% ggplot(aes(x = Sepal.Length, y = Petal.Length)) +
  geom_point(color = 'red') +
  geom_smooth(method = 'lm', color = 'green') +
  facet_wrap(~Species)

Vẽ đồ thị động

library(googledrive)
library(tidyverse)
library(gganimate)
library(magick)

pa <- 'https://drive.google.com/file/d/1Jc14iMyezkp0IARQdEPe03HbHh6NCiZA/view?usp=sharing'
id <- as_id(pa)
pa <- paste0('https://docs.google.com/uc?id=',id,'&export=download')
d <- read.csv(pa, header = T)
tmp <- d %>% filter(Country %in% c('Vietnam','Thailand','Malaysia', 'Cambodia', 'Laos'))
tmp <- tmp %>% select(Country,Population,Year)
tmp <- tmp %>% rename(country = Country ,pop = Population, year = Year)
tmp %>% ggplot(aes(x = year, y = pop, color = country)) +
  geom_line() +
  geom_point(size=2) +
  transition_reveal(year, keep_last = F)

Vẽ đồ thị động

Vẽ đồ thị cho một hàm số bất kỳ

Chúng ta có thể vẽ đồ thị cho một hàm số (toán học) bất kỳ mà chúng ta quan tâm như sau:

Chúng ta định nghĩa hàm số:

myfun <- function(xvar) { 1/(1 + exp(-xvar + 10))}

và vẽ đồ thị:

curve(myfun(x), from = -4, to = 6, col = 'red')

Vẽ đồ thị cho một hàm số bất kỳ (tt)

myfun1 <- function(x,a = 1.2){exp(x - a)/(1 + exp(x - a))}

Vẽ đồ thị:

curve(myfun1(x), from = -5, to = 5, col = "blue")
curve(1/x^2,from = .2,to = 6, add = T, col= "red")

Hàm qplot()

Sau khi chúng ta đã sử dụng hàm gglot() thành thạo thì gói ggplot2 có cung cấp cho chúng ta một lệnh hàm qplot() để rút ngắn hơn việc sử dụng hàm ggplot().

Cấu trúc của hàm qplot() một cách tổng quát:

qplot(x,y,...,data,facets = NULL,geom = "auto",stat = deprecated(),position = )

Một số ví dụ về việc sử dụng hàm qplot()

Hàm qplot() (tt)

qplot(color, data = diamonds, geom = 'bar', weight = carat)+ scale_y_continuous("carat")

Hàm qplot() (tt)

qplot(carat, data = diamonds, facets = color ~., geom = "histogram", binwidth = 0.1)

Hàm qplot() (tt)

qplot(x = carat, y = price, data = diamonds, color = cut)

Hàm qplot() (tt)

qplot(carat, data = diamonds, geom = "histogram", binwidth = 0.05)

Hàm qplot() (tt)

qplot(carat, data = diamonds, geom = "density")

Hàm qplot() (tt)

qplot(color, data = diamonds, geom = "bar", weight = carat) + scale_y_continuous("carat")