Thư viện ggplot2

chúng ta sẽ trực quan dữ liệu trên tập dữ dữ liệu gapminder

# import thư viện cần thiết để trực quan 
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(gapminder)

# nạp dữ liệu gapminder vào môi trường
data("gapminder")
head(gapminder)
## # A tibble: 6 × 6
##   country     continent  year lifeExp      pop gdpPercap
##   <fct>       <fct>     <int>   <dbl>    <int>     <dbl>
## 1 Afghanistan Asia       1952    28.8  8425333      779.
## 2 Afghanistan Asia       1957    30.3  9240934      821.
## 3 Afghanistan Asia       1962    32.0 10267083      853.
## 4 Afghanistan Asia       1967    34.0 11537966      836.
## 5 Afghanistan Asia       1972    36.1 13079460      740.
## 6 Afghanistan Asia       1977    38.4 14880372      786.
# tính tuổi thọ trung bình của các châu lục vào năm 2007 và sắp xếp tăng dần, hoặc giảm dần
gapminder %>% 
  filter(year == 2007) %>%
  group_by(continent) %>%
  mutate(mean_lifeExp = mean(lifeExp, na.rm=T)) %>%
  arrange(-mean_lifeExp) -> mean_lifeExp
mean_lifeExp
## # A tibble: 142 × 7
## # Groups:   continent [5]
##    country                continent  year lifeExp     pop gdpPercap mean_lifeExp
##    <fct>                  <fct>     <int>   <dbl>   <int>     <dbl>        <dbl>
##  1 Australia              Oceania    2007    81.2  2.04e7    34435.         80.7
##  2 New Zealand            Oceania    2007    80.2  4.12e6    25185.         80.7
##  3 Albania                Europe     2007    76.4  3.60e6     5937.         77.6
##  4 Austria                Europe     2007    79.8  8.20e6    36126.         77.6
##  5 Belgium                Europe     2007    79.4  1.04e7    33693.         77.6
##  6 Bosnia and Herzegovina Europe     2007    74.9  4.55e6     7446.         77.6
##  7 Bulgaria               Europe     2007    73.0  7.32e6    10681.         77.6
##  8 Croatia                Europe     2007    75.7  4.49e6    14619.         77.6
##  9 Czech Republic         Europe     2007    76.5  1.02e7    22833.         77.6
## 10 Denmark                Europe     2007    78.3  5.47e6    35278.         77.6
## # ℹ 132 more rows

sử dụng hàm arrange() để sắp xếp dữ liệu

các tham số trong hàm arrange(object, col1, col2,… group_by, .na.last)

+) object là tập dữ liệu chúng ta muốn sắp xếp, col1,col2 là cột chúng ta muốn dựa trên để sắp xếp…

+) thêm dấu trừ (-) vào trước cột dữ liệu để sắp xếp theo chiều giảm dần. và ngược lại

# chọn ra 5 nước có tuổi thọ trung bình cao nhất
head(arrange(mean_lifeExp, -mean_lifeExp))
## # A tibble: 6 × 7
## # Groups:   continent [2]
##   country                continent  year lifeExp      pop gdpPercap mean_lifeExp
##   <fct>                  <fct>     <int>   <dbl>    <int>     <dbl>        <dbl>
## 1 Australia              Oceania    2007    81.2 20434176    34435.         80.7
## 2 New Zealand            Oceania    2007    80.2  4115771    25185.         80.7
## 3 Albania                Europe     2007    76.4  3600523     5937.         77.6
## 4 Austria                Europe     2007    79.8  8199783    36126.         77.6
## 5 Belgium                Europe     2007    79.4 10392226    33693.         77.6
## 6 Bosnia and Herzegovina Europe     2007    74.9  4552198     7446.         77.6
# chọn ra 5 nước có tuổi thọ trung bình thấp nhất
head(arrange(mean_lifeExp, mean_lifeExp))
## # A tibble: 6 × 7
## # Groups:   continent [1]
##   country      continent  year lifeExp      pop gdpPercap mean_lifeExp
##   <fct>        <fct>     <int>   <dbl>    <int>     <dbl>        <dbl>
## 1 Algeria      Africa     2007    72.3 33333216     6223.         54.8
## 2 Angola       Africa     2007    42.7 12420476     4797.         54.8
## 3 Benin        Africa     2007    56.7  8078314     1441.         54.8
## 4 Botswana     Africa     2007    50.7  1639131    12570.         54.8
## 5 Burkina Faso Africa     2007    52.3 14326203     1217.         54.8
## 6 Burundi      Africa     2007    49.6  8390505      430.         54.8
# tìm ra 3 nước có tổng GDP cao nhất năm 2007
gapminder %>%
  filter(year == 2007) %>%
  group_by(country) %>%
  mutate(total = gdpPercap*pop) %>%
  arrange(-total)%>%
  head(n=3)
## # A tibble: 3 × 7
## # Groups:   country [3]
##   country       continent  year lifeExp        pop gdpPercap   total
##   <fct>         <fct>     <int>   <dbl>      <int>     <dbl>   <dbl>
## 1 United States Americas   2007    78.2  301139947    42952. 1.29e13
## 2 China         Asia       2007    73.0 1318683096     4959. 6.54e12
## 3 Japan         Asia       2007    82.6  127467972    31656. 4.04e12
# tìm ra 3 nước có tổng GDP thấp nhất năm 2007
gapminder %>%
  filter(year == 2007) %>%
  group_by(country) %>%
  mutate(total = gdpPercap * pop) %>%
  arrange(total) %>%
  head(n=3)
## # A tibble: 3 × 7
## # Groups:   country [3]
##   country               continent  year lifeExp     pop gdpPercap      total
##   <fct>                 <fct>     <int>   <dbl>   <int>     <dbl>      <dbl>
## 1 Sao Tome and Principe Africa     2007    65.5  199579     1598. 319014077.
## 2 Comoros               Africa     2007    65.2  710960      986. 701111696.
## 3 Guinea-Bissau         Africa     2007    46.4 1472041      579. 852652874.

Trực quan dữ liệu

1. Biểu đồ điểm (point)

chúng ta sử dụng thư viện gglot2 để trực quan dữ liệu

thư viện gglot2 biểu diễn dữ liệu trên cơ sở xếp trồng các layer

# lấy dữ liệu năm 2007 trong tập dữ liệu gapminder
gapminder2007 <- gapminder %>%
  filter(year == 2007)
gapminder2007
## # A tibble: 142 × 6
##    country     continent  year lifeExp       pop gdpPercap
##    <fct>       <fct>     <int>   <dbl>     <int>     <dbl>
##  1 Afghanistan Asia       2007    43.8  31889923      975.
##  2 Albania     Europe     2007    76.4   3600523     5937.
##  3 Algeria     Africa     2007    72.3  33333216     6223.
##  4 Angola      Africa     2007    42.7  12420476     4797.
##  5 Argentina   Americas   2007    75.3  40301927    12779.
##  6 Australia   Oceania    2007    81.2  20434176    34435.
##  7 Austria     Europe     2007    79.8   8199783    36126.
##  8 Bahrain     Asia       2007    75.6    708573    29796.
##  9 Bangladesh  Asia       2007    64.1 150448339     1391.
## 10 Belgium     Europe     2007    79.4  10392226    33693.
## # ℹ 132 more rows

Tạo biểu đồ trực quan lớp 1:

lớp 1 là một lớp trống chưa có phần từ sẽ được biểu diễn qua hàm ggplot

lớp 2 là lớp có thể là đường thẳng, cột, điểm được biểu diễn qua hàm geom_

hàm ggplot

# tìm mối liên hệ giữa tuổi thọ và thu nhập gdp trong năm 2007
# import thư viện ggplot2
library(ggplot2)
# tạo biểu đồ trực quan lớp 1
# tham số data: truyền tập dữ liệu mà chúng ta muốn trưc quan
# mapping = aes(x = gdpPercap, y = lifeExp)
# mapping sẽ ánh xạ dữ liệu từ cột gdpPercap và lifeExp vào trục x,y
ggplot(data = gapminder2007, mapping = aes(x = gdpPercap, y = lifeExp))

để thêm các lớp xếp trồng lên nhau chúng ta sử dụng toán tử (+)

hàm geom

# lớp 2 được biểu diễn qua hàm geom_
# vẽ các điểm trên trục
ggplot(data = gapminder2007, mapping=aes(x = gdpPercap, y = lifeExp))+
  geom_point(color = "indianred") # tham số color: indianred: là thiết lập màu sắc cho các điểm

# hàm geom_smooth: cho phép chúng ta kẻ đường hồi quy tuyến tính,...
ggplot(data = gapminder2007, mapping=aes(x = gdpPercap, y = lifeExp))+
  geom_point(color = "indianred")+
  geom_smooth(method = "loess", size =1.5)
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
## `geom_smooth()` using formula = 'y ~ x'

hàm scale

hàm scale cho phép chúng ta thay đổi giá trị của trục tọa độ,…

ggplot(data= gapminder2007, mapping = aes(x = gdpPercap, y = lifeExp))+
  geom_point(color = "indianred")+
  scale_x_log10() # scale_x_log10() là thay đổi giá trị trên trục x 

hàm labs

hàm labs cho phép chúng ta đặt tên title, trục x, y, caption,…

ggplot(data = gapminder, mapping = aes(x = gdpPercap, y = lifeExp, color = continent))+
  geom_point()+
  scale_x_log10()+
  labs(x = "Log GDP per Capita", 
     y = "Life Expectancy", 
     title = "Association between GDP and Life Expectancy")

  #ggtitle("Association between GDP and Life Expectancy") có thể dùng cách này
ggplot(data = gapminder, mapping = aes(x = gdpPercap, y = lifeExp, color = continent))+
  geom_point()+
  scale_x_log10()+
  labs(x = "Log GDP per Capita", 
     y = "Life Expectancy", 
     title = "Association between GDP and Life Expectancy")+
  geom_smooth(method = "loess",size = 1.5)
## `geom_smooth()` using formula = 'y ~ x'

Biểu đồ histogram: miêu tả phân phối xác suất của một biến liên tục

ggplot(data = gapminder2007, mapping = aes(gdpPercap))+
  geom_histogram(fill = "cornflowerblue", color = "black", bins = 10) # bins là chia số lượng quan sát thành số khoảng

# và tính toán quan sát trong mỗi khoảng

Biểu đồ bar

# so sánh tuổi thọ trung bình của các quốc gia Asia năm 2007
Asia2007 <- gapminder2007 %>%
  filter(continent == "Asia")

ggplot(data = Asia2007, mapping = aes(x = reorder(country, lifeExp), y = lifeExp, fill = country))+
  geom_bar(stat = "identity", width = 0.9)+
  labs(x = "", 
       y = "GDP Per Capita of Asia on 2007")+
  theme(legend.position = "none") # ẩn chú thích

như chúng ta đã thấy biểu đồ trên tên các quốc gia xếp đè lên nhau: (overlapping)

để tránh overlapping thông thường có 3 cách:

  1. xoay trục Ox và Oy

  2. xoay trục Ox một góc 45 độ

  3. tạo sự thụt lề giữa tên các quốc gia (staggering the labels)

Xoay trục Ox và Oy

# so sánh tuổi thọ trung bình của các quốc gia Asia năm 2007
Asia2007 <- gapminder2007 %>%
  filter(continent == "Asia")

ggplot(data = Asia2007, mapping = aes(x = reorder(country, lifeExp), y = lifeExp, fill = country))+
  geom_bar(stat = "identity", width = 0.9)+
  labs(x = "", 
       y = "GDP Per Capita of Asia on 2007")+
  theme(legend.position = "none")+ # ẩn chú thích
  coord_flip() # sử dụng coord_flip để xoay trục

xoay trục Ox một góc 45 độ

# so sánh tuổi thọ trung bình của các quốc gia Asia năm 2007
Asia2007 <- gapminder2007 %>%
  filter(continent == "Asia")

ggplot(data = Asia2007, mapping = aes(x = reorder(country, lifeExp), y = lifeExp, fill = country))+
  geom_bar(stat = "identity", width = 0.9)+
  labs(x = "", 
       y = "GDP Per Capita of Asia on 2007")+
  theme(legend.position = "none")+ # ẩn chú thích
  theme(axis.text.x = element_text(angle = 45, hjust = 1) )

biểu đồ segment

gapminder2007 %>%
  filter(continent == "Asia") -> asia2007

p1 <-ggplot(asia2007, mapping = aes(x = lifeExp, y = reorder(country, lifeExp)))+
  geom_point(stat = "identity", color = "blue", size=2)+
  geom_segment(aes(x=40, xend = lifeExp, y = reorder(country, lifeExp),
               yend = reorder(country, lifeExp), color = "red"))+
  labs(x = "Life Expectancy of Asia on 2007", 
       y = "")+
  theme_minimal()+
  scale_x_continuous(breaks = seq(40,90,5), limits = c(40,90))+
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) # xóa ô trống
p1

2. Các thư viện hộ trợ việc hiển thị

2.1 thư viện GridExtra

thư viện girdExtra cho phép hiển thị số biểu đồ dựa trên dạng lưới

library(gridExtra)
## 
## Attaching package: 'gridExtra'
## The following object is masked from 'package:dplyr':
## 
##     combine
Asia2007 <- gapminder2007 %>%
  filter(continent == "Asia")

graph1 <- ggplot(data = Asia2007, mapping = aes(x = reorder(country, lifeExp), y = lifeExp, fill = country))+
  geom_bar(stat = "identity", width = 0.9)+
  labs(x = "", 
       y = "GDP Per Capita of Asia on 2007")+
  theme(legend.position = "none")+ # ẩn chú thích
  coord_flip() # sử dụng coord_flip để xoay trục


graph2 <- ggplot(data = Asia2007, mapping = aes(x = reorder(country, gdpPercap), y = gdpPercap, fill = country))+
  geom_bar(stat = "identity", width = 0.9)+
  labs(x = "", 
       y = "GDP Per Capita of Asia on 2007")+
  theme(legend.position = "none")+ # ẩn chú thích
  coord_flip() # sử dụng coord_flip để xoay trục

grid.arrange(graph1, graph2, ncol = 2)

2.2 Thư viện plotly

biểu diễn biểu đồ dưới dạng dynamic

library(plotly)
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
gapminder2007 %>%
  filter(continent == "Asia") -> asia2007

p1 <-ggplot(asia2007, mapping = aes(x = lifeExp, y = reorder(country, lifeExp)))+
  geom_point(stat = "identity", color = "blue", size=2)+
  geom_segment(aes(x=40, xend = lifeExp, y = reorder(country, lifeExp),
               yend = reorder(country, lifeExp), color = "red"))+
  labs(x = "Life Expectancy of Asia on 2007", 
       y = "")+
  theme_minimal()+
  scale_x_continuous(breaks = seq(40,90,5), limits = c(40,90))+
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) # xóa ô trống
p1

ggplotly(p1)

2.3 thư viện ggthemes

thư viện ggthemes cho phép biểu diễn biểu đồ dưới dạng chuẩn của bài báo economic của my

library(ggthemes)

Asia2007 <- gapminder2007 %>%
  filter(continent == "Asia")

ggplot(data = gapminder, mapping = aes(x = gdpPercap, y = lifeExp, color = continent))+
  geom_point()+
  scale_x_log10()+
  labs(x = "Log GDP per Capita", 
     y = "Life Expectancy", 
     title = "Association between GDP and Life Expectancy")+
  theme_economist()