Đồ thị được vẽ theo code sau:
# Load necessary library
library(ggplot2)
library(ggthemes)
library(plotly)
library(grid)
library(dplyr)
# Define the data
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)
data_bar <- data.frame(virus = virus_names, n = my_number)
# Define the grouping variable based on the values of n
data_bar$group <- cut(data_bar$n, breaks = c(0, 10, 20, Inf ),
labels = c( "Low", "Medium","High"))
# Define the colors for each group
colors <- c("#EBB434", "#3EBCD2", "#006BA2")
# Create the bar graph
ggplot(data = data_bar, aes(x = n, y = reorder(virus, n), fill = group)) +
geom_vline(xintercept = c(10, 20), linetype = "dashed", color = "black") +
geom_bar(stat = "identity", width = 0.8) +
scale_x_continuous(breaks = seq(0, 55, by = 10), position = "top") +
scale_fill_manual(values = c("#EBB434", "#3EBCD2", "#006BA2"),
labels = c("Low", "Medium", "High"),
guide = guide_legend(reverse = TRUE)) +
theme_economist() +
theme(plot.title = element_text(family = "Econ Sans",hjust = 0.5, vjust = .5, size = 16, face = "bold"),
plot.subtitle = element_text(margin = margin(b = 10), hjust = 0.5, vjust = .7, face = "italic"),
axis.title = element_blank(),
axis.text.y = element_text(size = 11),
axis.text.x = element_text(size = 11),
axis.line = element_line(color = "black"),
axis.title.x = element_blank(),
panel.grid.major = element_line(color = "#d5e4eb"),
panel.grid.minor = element_blank(),
panel.background = element_rect(fill = "#d5e4eb"),
panel.border = element_blank(),
legend.position = c(0.85, 0.45),
legend.background = element_rect(fill = "#d5e4eb"),
legend.title = element_blank(),
legend.text = element_text(size = 11),
legend.key.height = unit(0.5, "cm"),
plot.caption = element_text(face = "italic", size = 12, hjust = 1)
) +
# ggtitle("Popularity of viruses (Number of cases)") +
labs(
title = "Popularity of viruses (Number of cases)",
subtitle = "Source: World Health Organization",
caption = "Designer: Dai Duong", fontface = "italic") +
coord_cartesian(xlim = c(0, 60)) +
geom_text(aes(label = n), hjust = 1.2, vjust = 0.4, color = "yellow",fontface = "bold",
data = data_bar %>% group_by(group) %>% slice_max(n),
show.legend = FALSE) -> p
red_icon <- "#ed1c24"
p
grid.rect(x = 0.035, y = 1, width = 0.05, height = 0.008*2.5, just = c("left", "top"), gp = gpar(fill = red_icon, col = red_icon))Kết quả không đẹp lắm.
ggplotly(p).