查看原文
其他

R可视化:双向条形图

阿越就是我 医学和生信笔记 2023-06-15
关注公众号,发送R语言python,可获取资料

医学和生信笔记,专注R语言在临床医学中的使用、R语言数据分析和可视化。主要分享R语言做医学统计学、临床研究设计、meta分析、网络药理学、临床预测模型、机器学习、生物信息学等

💡专注R语言在🩺生物医学中的使用


本系列内容来自github上面超级火爆的R语言可视化项目:tidyTuesday。是学习R语言数据分析和可视化极好的素材。

  • CSDN项目地址:数绘小站的博客_CSDN博客-Tidy Tuesday[1]

我只是搬运工,感谢小伙伴的分享。


本次是条形图,双向条形图。

Tidy Tuesday 在 GitHub 上的传送地址:Thomas Mock (2022). Tidy Tuesday: A weekly data project aimed at the R ecosystem. https://github.com/rfordatascience/tidytuesday

1. 一些环境设置

# 设置为国内镜像, 方便快速安装模块
options("repos" = c(CRAN = "https://mirrors.tuna.tsinghua.edu.cn/CRAN/"))

2. 设置工作路径

wkdir <- '/home/user/R_workdir/TidyTuesday/2018/2018-04-02_US_Tuition_Costs/src-b'
setwd(wkdir)

3. 加载 R 包

library(tidyverse)
library(lubridate)
library(showtext)
# 在 Ubuntu 系统上测试的, 不加这个我画出来的汉字会乱码 ~
showtext_auto()

4. 加载数据

df_input <- readxl::read_excel("../data/us_avg_tuition.xlsx")

# 简要查看数据内容
glimpse(df_input)
## Rows: 50
## Columns: 13
## $ State     <chr> "Alabama", "Alaska", "Arizona", "Arkansas", "California", "C…albert
## $ `2004-05` <dbl> 5682.838, 4328.281, 5138.495, 5772.302, 5285.921, 4703.777, …
## $ `2005-06` <dbl> 5840.550, 4632.623, 5415.516, 6082.379, 5527.881, 5406.967, …
## $ `2006-07` <dbl> 5753.496, 4918.501, 5481.419, 6231.977, 5334.826, 5596.348, …
## $ `2007-08` <dbl> 6008.169, 5069.822, 5681.638, 6414.900, 5672.472, 6227.002, …
## $ `2008-09` <dbl> 6475.092, 5075.482, 6058.464, 6416.503, 5897.888, 6284.137, …
## $ `2009-10` <dbl> 7188.954, 5454.607, 7263.204, 6627.092, 7258.771, 6948.473, …
## $ `2010-11` <dbl> 8071.134, 5759.153, 8839.605, 6900.912, 8193.739, 7748.201, …
## $ `2011-12` <dbl> 8451.902, 5762.421, 9966.716, 7028.991, 9436.426, 8315.632, …
## $ `2012-13` <dbl> 9098.069, 6026.143, 10133.503, 7286.580, 9360.574, 8792.856,…
## $ `2013-14` <dbl> 9358.929, 6012.445, 10296.200, 7408.495, 9274.193, 9292.954,…
## $ `2014-15` <dbl> 9496.084, 6148.808, 10413.844, 7606.410, 9186.824, 9298.599,…
## $ `2015-16` <dbl> 9751.101, 6571.340, 10646.278, 7867.297, 9269.844, 9748.188,…
# 检查数据的列名
colnames(df_input)
##  [1] "State"   "2004-05" "2005-06" "2006-07" "2007-08" "2008-09" "2009-10"
##  [8] "2010-11" "2011-12" "2012-13" "2013-14" "2014-15" "2015-16"

5. 数据预处理

# 将列名简化, 方便绘图展示
df_tidy <- gather(df_input, key = Year, value = Tuition, -State)

# 调整年份为 YYYY 格式
df_tidy <- 
    df_tidy %>% 
    mutate(Year = str_sub(Year, start = 1, end = 4))

5. 条形图 (一)

5.1 以 state 为分组取平均值

df_plot_1 <-
    df_tidy %>% 
    select(State, Tuition) %>% 
    group_by(State) %>% 
    # 最好使用 dplyr::summarise() 形式调用函数, 不然容易和内置函数冲突
    dplyr::summarise(Mean_State = mean(Tuition)) %>% 
    arrange(desc(Mean_State))

5.2. 用 ggplot2 开始绘图

# PS: 方便讲解, 我这里进行了拆解, 具体使用时可以组合在一起
gg <- ggplot(df_plot_1)
# geom_bar() 绘制条形图
gg <- gg + geom_bar(aes(x = reorder(State, Mean_State), y = Mean_State), 
                    stat = "identity"
                    position = "dodge"
                    fill = "cadetblue3")
# coord_flip() 倒置坐标系
gg <- gg + coord_flip()
# theme_minimal() 去坐标轴边框的最小化主题
gg <- gg + theme_minimal()
gg <- gg + labs(title = "美国各个州的大学学费变化",
                x = NULL,
                y = NULL)
# theme() 实现对非数据元素的调整, 对结果进行进一步渲染, 使之更加美观
gg <- gg + theme(
  # panel.grid.major 主网格线, 这一步表示删除主要网格线
  panel.grid.major = element_blank(),
  # panel.grid.minor 次网格线, 这一步表示删除次要网格线
  panel.grid.minor = element_blank(),
  # axis.text 坐标轴刻度文本
  axis.text = element_text(color = "black", size = 12),
  # axis.title 坐标轴标题
  axis.title = element_text(color = "black", size = 10),
  # plot.title 主标题
  plot.title = element_text(color = "black", size = 20, face = "bold"),
  # plot.subtitle 次要标题
  plot.subtitle = element_text(color = "red", size = 12),
  # plot.background 图片背景
  plot.background = element_rect(fill = "white"))

5.3 保存图片到 PDF 和 PNG

gg
在这里插入图片描述
filename = '20180402-B-01'
ggsave(filename = paste0(filename, ".pdf"), width = 8.6, height = 12, device = cairo_pdf)
ggsave(filename = paste0(filename, ".png"), width = 8.6, height = 12, dpi = 100, device = "png")

6. 条形图 (二)

6.1 以 state 为分组取平均值, 并分类

# 以 state 为分组取平均值, 并以总均值划分为两类
df_plot_2 <-
    df_tidy %>% 
    group_by(State) %>% 
    # 建议使用 dplyr::mutate 形式调用函数, 不然容易与 plyr 中的函数冲突 (因为我自己就报错了...)
    dplyr::mutate(Mean_State = mean(Tuition)) %>% 
    ungroup() %>% 
    dplyr::mutate(Classify = Mean_State - mean(Mean_State)) %>% 
    dplyr::mutate(Category = ifelse(Classify < 0"低于平均值""高于平均值")) %>% 
    arrange(desc(Classify)) %>% 
    select(State, Classify, Category) %>% 
    distinct()

6.2. 用 ggplot2 开始绘图

# PS: 方便讲解, 我这里进行了拆解, 具体使用时可以组合在一起
gg <- ggplot(df_plot_2)
# geom_bar() 绘制条形图
gg <- gg + geom_bar(aes(x = reorder(State, -Classify), y = Classify, fill = Category),
                    stat = "identity",
                    position = "dodge")
gg <- gg + geom_hline(yintercept = 0, linetype = 2)
# coord_flip() 倒置坐标系
gg <- gg + coord_flip()
gg <- gg + scale_fill_brewer()
# theme_minimal() 去坐标轴边框的最小化主题
gg <- gg + theme_minimal()
gg <- gg + labs(title = "美国各个州的大学学费变化",
                x = NULL,
                y = NULL)
# theme() 实现对非数据元素的调整, 对结果进行进一步渲染, 使之更加美观
gg <- gg + theme(
  # panel.grid.major 主网格线, 这一步表示删除主要网格线
  panel.grid.major = element_blank(),
  # panel.grid.minor 次网格线, 这一步表示删除次要网格线
  panel.grid.minor = element_blank(),
  # axis.text 坐标轴刻度文本
  axis.text = element_text(color = "black", size = 12),
  # axis.title 坐标轴标题
  axis.title = element_text(color = "black", size = 10),
  # plot.title 主标题
  plot.title = element_text(color = "black", size = 20, face = "bold"),
  # plot.subtitle 次要标题
  plot.subtitle = element_text(color = "red", size = 12),
  # plot.background 图片背景
  plot.background = element_rect(fill = "white"))

6.3 保存图片到 PDF 和 PNG

gg
在这里插入图片描述
filename = '20180402-B-02'
ggsave(filename = paste0(filename, ".pdf"), width = 8.6, height = 12, device = cairo_pdf)
ggsave(filename = paste0(filename, ".png"), width = 8.6, height = 12, dpi = 100, device = "png")

测试数据

配套数据下载:us_avg_tuition.xlsx[2]

本次内容来自CSDN,我只是搬运工,项目地址:数绘小站的博客_CSDN博客-Tidy Tuesday[3]

参考资料

[1]

CSDN项目地址: https://blog.csdn.net/Albert_XN?type=blog

[2]

数据下载: https://gitee.com/tidytuesday/tt-data/blob/master/2018/2018-04-02

[3]

CSDN项目地址: https://blog.csdn.net/Albert_XN?type=blog




咨询交流等,欢迎加入🐧QQ交流群:613637742




往期推荐



今天你emo了吗?

使用scales自定义图形标签和刻度

使用lubridate处理日期时间

使用dplyr进行数据分析:入门篇

dplyr强大的分组汇总

dplyr中的across操作

dplyr中的行操作

数据变为长数据的5种情况!

长数据变为宽数据的7种情况!

长数据变为宽数据的7种情况!

分组、离断式坐标轴

ggplot2修改坐标轴详细介绍

ggplot2分面图形大改造

超详细教程:修改ggplot2图例

让你的ggplot2支持markdown语法

ggplot2绘制突变全景图

ggplot2画泳道图箭头如何显示

ggplot2画肿瘤领域常见的泳道图

ggplot2可视化拷贝数变异CNV的GISTIC score


您可能也对以下帖子感兴趣

文章有问题?点此查看未经处理的缓存