加载R包
代码语言:javascript
复制library(tidyverse)
library(stringr)
library(reshape2)
library(ggtext)
library(ggh4x)
导入数据
代码语言:javascript
复制life_expectancy <- read_csv("life_expectancy.csv")
数据清洗
代码语言:javascript
复制df <- life_expectancy %>% filter(Entity %in% c("Asia","Europe","Africa","Oceania","United States",
"High-income countries",
"Middle-income countries","Lower-middle-income countries",
"Low-income countries","World")) %>%
select(-Code) %>%
pivot_wider(names_from = "Entity",values_from = "LifeExpectancy") %>%
melt(id.vars = c("Year", "World"),
variable.factor = FALSE, value.factor = FALSE,
variable.name = "Entity", value.name = "LifeExpectancy")
df2 = df %>% dplyr::rename("Entity2"="Entity")
数据可视化
代码语言:javascript
复制ggplot(data = df)
geom_line(data = df2, aes(Year, LifeExpectancy, group = Entity2),color = "grey85", linewidth = .65)
geom_line(aes(Year, LifeExpectancy, group = Entity, color = "Entity"),linewidth = .65)
geom_line(aes(Year, World, group = 1, color = "World"),linewidth = .65)
scale_color_manual(values = c("World" = "#0064ee", "Entity" = "#ee1300"))
scale_x_continuous(limits = c(1950, 2021), expand = c(0, 0), breaks = seq(1950, 2021, by = 20))
facet_wrap2(vars(Entity), ncol = 3, axes = "all")
theme_minimal()
theme(
legend.position = "bottom",
legend.justification = "left",
legend.title = element_blank(),
strip.text = element_text(face = "bold", hjust = 0.5, size = 10),
panel.spacing = unit(1.5, "lines"),
panel.grid.major = element_line(linetype = "dashed", linewidth = .35, color = "grey85"),
panel.grid.minor = element_line(linetype = "dashed", linewidth = .25, color = "grey85"),
axis.ticks.y = element_line(linewidth = .35, color = "grey85"),
axis.title.x = element_blank(),
axis.title.y = element_text(hjust = 0.5, margin = margin(r = 10)),
axis.text.x = element_text(size = 8),
plot.background = element_rect(fill = "#f5f5f5", color = NA),
plot.margin = margin(10, 10, 10, 10))