#Vẽ biểu đồ (ggplot2) ##1. lấy data từ gapminder package ‘gapminder’ successfully unpacked and MD5 sums checked

library(gapminder)
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.

##2.Vẽ biểu đồ tương quan

 library(ggplot2)
 p=ggplot(data=gapminder,aes(x=gdpPercap, y=lifeExp))

###Gõ P để hiện biểu đồ ###Vẽ biểu đồ hiện point

 p=ggplot(data=gapminder,aes(x=gdpPercap, y=lifeExp))
 p = p + geom_point ()
 p

#vẽ biểu đồ line, smooth thể hiện đường cong tương quan.

 p=ggplot(data=gapminder,aes(x=gdpPercap, y=lifeExp))
 p = p + geom_point ()
 p = p + geom_line ()
 p

 p = p + geom_line () + geom_smooth()
 p
## `geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'

vẽ biểu đồ có màu lục địa

 p=ggplot(data=gapminder,aes(x=gdpPercap, y=lifeExp,color=continent))
 p=p+geom_smooth(method = "loess")
 p
## `geom_smooth()` using formula = 'y ~ x'

###Hàm vẽ tổng

  p = ggplot(data = gapminder, aes(x = gdpPercap, y = lifeExp) )
 p = p + geom_point(aes(color=continent))
 p = p + geom_smooth (method="loess") + scale_x_log10()
 p
## `geom_smooth()` using formula = 'y ~ x'

VẼ BIỂU ĐỒ PHÂN Bố

##1.Lấy data

tq=read.csv( "D:\\OneDrive\\Documents\\HPK1 2018\\NVPS2025\\Viết báo khoa học paper\\R\\DU LIEU THUC HANH\\CHNS data full.csv")
head(tq)
##   id whours wgroup dead fu.time gender age edu marital residence income occu
## 1  1     35      1    0       4      2  52   3       3         1 116000    1
## 2  2     48      3    0       4      1  36   3       2         1  25200    1
## 3  3     40      1    0       4      2  31   3       2         1  27000    1
## 4  4     48      3    0       4      2  51   2       2         1  27600    2
## 5  5     32      2    0       4      1  58   2       2         1  34800    2
## 6  6     40      1    0       4      1  42   3       2         1  77000    1
##   smoking drinking height weight   bmi sys1 sys2 sys3 dias1 dias2 dias3 tsf1
## 1       0        0    168   83.5 29.58  120  126  120    80    82    76   28
## 2       1        0    173   85.0 28.40  120  120  120    90    80    80   25
## 3       0        1    167   50.0 17.93  110  108  110    70    70    70   18
## 4       0        0    164   80.0 29.74  120  110  120    80    82    80   27
## 5       0        0    175   65.0 21.22  120  120  120    80    82    80   23
## 6       0        1    179   75.0 23.41  110  112  110    72    76    70   24
##   tsf2 tsf3 uac  hc  wc
## 1   27   28  36 111 103
## 2   44   25  35 102  95
## 3   17   18  25  96  72
## 4   26   27  32 104  97
## 5   22   22  35 102  90
## 6   23   24  28  96  90

##2. Vẽ biểu đồ phân phối đơn giản

p=ggplot(data = tq, aes(x=income))
p

p+geom_histogram()
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## Warning: Removed 224 rows containing non-finite outside the scale range
## (`stat_bin()`).

##3.vẽ màu cho biểu đồ

p+geom_histogram(fill="blue",col="yellow")
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## Warning: Removed 224 rows containing non-finite outside the scale range
## (`stat_bin()`).

##4.Vẽ biểu đồ theo log để thấy được tương quan

p = ggplot(data=tq, aes(x=log(income)))
p+geom_histogram(fill="green",col="white")
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## Warning: Removed 241 rows containing non-finite outside the scale range
## (`stat_bin()`).

##5. Điền nhãn cho trục hoành, trục tung

p = ggplot(data = tq, aes(x = log(income)))
p+ geom_histogram(fill = "violet",col = "yellow")+labs(x = "income (logscale)",y = "Frequency")
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## Warning: Removed 241 rows containing non-finite outside the scale range
## (`stat_bin()`).

##6. Mục tiêu, hiển thị income theo giới tính

p = ggplot(data=tq, aes (x =log(income), fill =factor(gender) ) )
p + geom_histogram(col="white") +
     labs (x="Income log(scale)",y="Frequency", title="Phan bo thu nhập")
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## Warning: Removed 241 rows containing non-finite outside the scale range
## (`stat_bin()`).

##7. vẽ theo mật độ hay tỷ lệ %, frequency, làm mờ alpha =0.5 để thấy 2 đường biểu diễn

 p + geom_density(alpha=0.5) +labs (x="Income log(scale)", y="Frequency", title = "Phân bố thu nhập")
## Warning: Removed 241 rows containing non-finite outside the scale range
## (`stat_density()`).

##8.Biều đồ thanh

library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.5
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ lubridate 1.9.4     ✔ tibble    3.2.1
## ✔ purrr     1.0.4     ✔ tidyr     1.3.1
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors

###8.1. Tạo data thu nhập theo độ tuổi

temp = tq %>% group_by(edu) %>% summarise(income = median(income, na.rm = T))
temp
## # A tibble: 3 × 2
##     edu income
##   <int>  <dbl>
## 1     1  1750.
## 2     2  6420 
## 3     3 31200

kết quả

1 1750. 2 6420 3 31200 ##9.vẽ biểu đồ thanh

tq$edu = as.character(factor(tq$edu, levels = c(1, 2, 3), labels = c("Primary", "Secondary", "Tertary")))
p = ggplot(data = temp, aes(x = edu, y = income, fill = edu))
p1 = p + geom_bar(stat = "identity") + labs(x = "Education", y = "Income") + theme(legend.position = "none")
p1

###9.1. Vẽ biểu đồ thanh có legend ( tiêu đề trên cột)

p + geom_bar(stat = "identity") + geom_text(aes(label = income, vjust = -0.5)) + geom_bar(stat = "identity") + labs(x = "Education", y = "Income") + theme(legend.position="none")

##10Soạn biểu đồ hộp so sánh phân bố của thu nhập theo giới tính “tq” tự đặt.

tq$gender = as.character(factor(tq$gender, levels = c(1, 2), labels = c("Men", "Women")))
p = ggplot(data = tq, aes(x = factor(gender), y = log(income), col = factor(gender)))
p + geom_boxplot() + geom_jitter(alpha = 0.05) + labs(x = "Giới tính", y = "Thu nhập (logarithm scale)") + ggtitle("Thu nhập theo giới tính")
## Warning: Removed 241 rows containing non-finite outside the scale range
## (`stat_boxplot()`).
## Warning: Removed 224 rows containing missing values or values outside the scale range
## (`geom_point()`).

##11. Soạn biểu đồ tương quan ###11.1.Mối liên quan giữa thu nhập và tuổi

p = ggplot(data = tq, aes(x = age, y = log(income)))
p + geom_point() + labs(x = "Tuổi", y = "Thu nhập (logarithm scale)") + ggtitle("Thu nhập theo tuổi")
## Warning: Removed 226 rows containing missing values or values outside the scale range
## (`geom_point()`).

###11.2. Mối liên quan giữa thu nhập và tuổi theo giới tính.

p = ggplot(data = tq, aes(x = age, y = log(income), col = factor(gender)))
p1 = p + geom_point() + labs(x = "Tuổi", y = "Thu nhập (logarithm scale)") + ggtitle("Mối liên quan giữa thu nhập và tuổi theo giới tính")
p1
## Warning: Removed 226 rows containing missing values or values outside the scale range
## (`geom_point()`).

###11.3. Thêm đường mô tả mối liên quan smooth

 p2 = p1 + geom_smooth()
 p2
## `geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'
## Warning: Removed 243 rows containing non-finite outside the scale range
## (`stat_smooth()`).
## Warning: Removed 226 rows containing missing values or values outside the scale range
## (`geom_point()`).

### Đường tương quan bậc 3

p3 = p1 + geom_smooth(method = "lm", formula = y ~ x + I(x^2) + I(x^3))
p3
## Warning: Removed 243 rows containing non-finite outside the scale range
## (`stat_smooth()`).
## Warning: Removed 226 rows containing missing values or values outside the scale range
## (`geom_point()`).

##Kết thúc