前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >[GBD数据库挖掘] 14.ggplot2优雅展示预期寿命数据

[GBD数据库挖掘] 14.ggplot2优雅展示预期寿命数据

作者头像
R语言数据分析指南
发布2023-12-13 15:58:27
3610
发布2023-12-13 15:58:27
举报
文章被收录于专栏:R语言数据分析指南

加载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)) 
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2023-12-12,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 R语言数据分析指南 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 加载R包
  • 导入数据
  • 数据清洗
  • 数据可视化
相关产品与服务
数据库
云数据库为企业提供了完善的关系型数据库、非关系型数据库、分析型数据库和数据库生态工具。您可以通过产品选择和组合搭建,轻松实现高可靠、高可用性、高性能等数据库需求。云数据库服务也可大幅减少您的运维工作量,更专注于业务发展,让企业一站式享受数据上云及分布式架构的技术红利!
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档