Tạo dữ liệu

#Clear R environment: 

rm(list = ls())

# Data for ploting: 

virus_names <- c("Hantavirus", "Tularemia", "Dengue", "Ebola", "E. coli", 
                 "Tuberculosis", "Salmonella", "Vaccinia", "Brucella")

my_number <- c(6, 7, 7, 9, 11, 15, 17, 18, 54)

axixx <- c(0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55)

data.frame(virus = virus_names, n = my_number) -> data_bar
#goi thu vien
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")

#Sap xep du lieu

data_bar %>% arrange(n) -> data_bar
data_bar %>% mutate(virus=factor(virus, level=virus))->data_bar

#Chọn font chữ

library("showtext")
## Warning: package 'showtext' was built under R version 4.2.3
## Loading required package: sysfonts
## Loading required package: showtextdb
my_font <- "Roboto Slab"
font_add_google(name = my_font, family = my_font)
showtext_auto()

Cài đặt chữ trong plot

data_bar %>% pull(virus)-> data2
group3 <- c("Hantavirus", "Tularemia", "Dengue")
case_when(data2 %in% group3 ~ -1.7, TRUE ~ 0.1) -> text_hjust
case_when(data2 %in% group3 ~ "#056fa1", TRUE ~ "white") -> text_color

Vẽ

ggplot(data = data_bar, aes(x=n, y=virus))+
  geom_col(fill = "#076f9f", width = 0.5)+
  geom_text(aes(y= virus, x = 1.5, label=virus),color = text_color, size=6, hjust=text_hjust)+
  theme(panel.grid.major.y = element_blank())+
  scale_x_continuous(breaks = c(0,5,10,15,20,25,30,35,40,45,50),expand = c(0, 0), position = "top")+
  theme(axis.ticks = element_blank())+
  theme(axis.title.y = element_blank(), axis.title.x = element_blank())+
  labs(title = "Escape artists", subtitle = "Number of laboratory-acquired infections, 1970-2021",
       caption = "Source: Aboratory-acquired infection database, American Biology Safety Association")+
  theme(plot.title = element_text(hjust = 0, face = "bold", size = 22, family = my_font))+
  theme(plot.subtitle = element_text(hjust =0, size = 17, family = my_font))+
  theme(plot.caption = element_text(hjust = 0, color = "grey", family = my_font, size = 15))+
  theme(axis.text.y = element_blank())+
  theme(panel.background = element_rect(fill = "white"))+
  theme(panel.grid.major.x = element_line(colour = "#a7b9c4"))+
  geom_vline(xintercept = 0, color = "black")+
  theme(plot.margin = unit(rep(0.5, 4), "cm"))

Kết quả