#Practice R
Bài thực hành được lấy từ Báo cáo PCI2018. Bài tuy còn nhiều thiếu sót nhưng các bạn cũng có thể tham khảo nhé.
Bài viết này được tham khảo trong quá trình học tập bởi Thầy Nguyễn Chí Dũng!
library(readxl)
library(viridis)
library(tidyverse)
rm(list = ls())
df_raw <- read_excel("D:\\R\\Day3\\du-lieu-pci-2018.xlsx")
df_raw %>% slice(1:63) %>% select(1:3) -> df_raw
#rename
names(df_raw) <- c("Province", "Rank", "Score")
df_raw %>%
mutate(Province = case_when(str_detect(Province, "BRVT") ~ "Bà Rịa - Vũng Tàu",
TRUE ~ Province)) %>%
mutate(Rank_m = case_when(Rank < 10 ~ paste0("0", Rank), TRUE ~ as.character(Rank))) %>%
mutate(Province = paste(Province, Rank_m)) %>%
mutate(df_sort = case_when(Rank <= 2 ~ "Rất tốt",
Rank >= 3 & Rank <= 9 ~ "Tốt",
Rank >= 10 & Rank <= 41 ~ "Khá",
Rank >= 42 & Rank <= 61 ~ "Trung Bình",
TRUE ~ "Thấp")) %>% arrange(-Rank) -> df_raw
df_raw %>%
mutate(Province = factor(Province, levels = Province)) %>%
mutate(df_sort = factor(df_sort, levels = df_sort %>% unique() %>% .[5:1]))-> df_raw
df_raw %>%
mutate(mix = round(Score, 2) %>% as.character()) %>%
mutate(mix = case_when(str_count(mix) == 2 ~ paste0(mix, ".00"),
str_count(mix) == 4 ~ paste0(mix, "0"),
TRUE ~ mix))-> df_final
#plots
my_font <- "Roboto Condensed"
df_final %>%
ggplot(aes(x = Province, y = Score, fill = df_sort)) +
geom_col(width = 0.75) +
coord_flip() +
scale_fill_viridis(discrete = TRUE, name = "", option = "D")+
geom_text(aes(label = mix), size = 2.5, hjust = -0.2) +
scale_y_continuous(limits = c(0,80), expand = c(0,0)) +
theme_minimal() +
theme(axis.text.x = element_blank()) +
theme(axis.text.y = element_text(size = 6.4, family = my_font, color = "black")) +
theme(axis.ticks.y = element_blank()) +
theme(panel.grid = element_blank()) +
theme(axis.title = element_blank()) +
theme(panel.border = element_blank()) +
theme(plot.title = element_text(family = my_font, color = "grey20", size = 22,
face = "bold")) +
theme(plot.caption = element_text(family = my_font, size = 11, colour = "grey20", face = "italic")) +
theme(legend.text = element_text(family = my_font, size = 10)) +
theme(plot.margin = unit(c(1, 1, 1, 2), "cm")) +
labs(x= NULL, y = NULL,
title = "Vietnam CPI Index 2018",
caption = "Data Source: http://pci2018.pcivietnam.vn")