woodcorpse的个人博客分享 http://blog.sciencenet.cn/u/woodcorpse

博文

ggplot2:9绘图需要的数据整理技术-数据转换

已有 3241 次阅读 2018-6-2 11:32 |个人分类:R|系统分类:科研笔记

ggplot2绘图基础系列:

# 加载本文所需包
library(lubridate)
library(magrittr)
library(dplyr)
library(tidyr)

# 查看测试数据结果
ggplot2::economics
# 整理数据为按月与年同期变化的数据表
ec2 = ggplot2::economics %>%
  tbl_df() %>%
  transmute(year = year(date), month = month(date), rate = uempmed) %>%
  filter(year > 2005) %>% 
  spread(year, rate)
ec2



# 数据转换spread(索引数据变矩阵/笛卡尔数据)和gather(矩阵变索引)示例

# 创建索引类型的
indexed = data.frame(
  x = c("a", "b", "c", "d", "c"),
  y = c("A", "D", "A", "C", "B"),
  z = c(1, 5, 4, 9, 10)
) 
# 排序x, y字母顺序排序
indexed = indexed %>% arrange(x,y)
indexed
# 表格展示
knitr::kable(indexed)

# speard 索引转换为矩阵/笛卡尔坐标系
matrix = indexed %>% spread(y, z)
knitr::kable(matrix)


# gather()函数包含以下四个参数:
# 
# data:需要转换的数据集
# 
# key:将从列名创建出的变量名称
# 
# value:将从每个单元创建出的变量名
# 
# ...:要收集哪些变量,可以一个一个列出来,也可以使用简写形式 ..:..

# gather将笛卡尔数据转换为索引数据
indexed = gather(ec2, key = year, value = unemp, `2006`:`2015`)
indexed = gather(ec2, key = year, value = unemp, -month,
                 convert = T, na.rm = T) # 自动将年份从字符串转换为数字,删除没有数据的月份
head(indexed)


# 绘制折线图
# 在不同年份分组下,每月失业率变化 
library(ggplot2)
ggplot(indexed, aes(month, unemp, group = year)) +
  geom_line(aes(colour = year), size = 1)

# 按时间和月份变化,直接使用两列属性组合
ggplot(indexed, aes(year + (month-1)/12, unemp)) +
         geom_line()



# Spread 转换索引数据为笛卡尔数据

weather = dplyr::data_frame(
  day = rep(1:3, 2),
  obs = rep(c("temp", "rain"), each = 3),
  val = c(c(23, 22, 20), c(0, 0, 5))
)
weather
spread(weather, key = obs, value = val)



# Separate and Unite拆分或合并属性
trt = dplyr::data_frame(
  var = paste0(rep(c("beg", "end"), each = 3), "_", rep(c("a","b","c"))),
  val = c(1, 4, 2, 10, 5, 11)
)


# 将第一列var拆分为两列
trt.sep = separate(trt, var, c("time", "treatment"), "_")
trt.sep

# 将两列合并为一列,默认为下划线
unite(trt.sep, "var", c("time", "treatment"))

猜你喜欢

写在后面

为鼓励读者交流、快速解决科研困难,我们建立了“宏基因组”专业讨论群,目前己有国内外1500+ 一线科研人员加入。参与讨论,获得专业解答,欢迎分享此文至朋友圈,并扫码加主编好友带你入群,务必备注“姓名-单位-研究方向-职称/年级”。技术问题寻求帮助,首先阅读《如何优雅的提问》学习解决问题思路,仍末解决群内讨论,问题不私聊,帮助同行。
image

学习扩增子、宏基因组科研思路和分析实战,关注“宏基因组”
image
点击阅读原文,跳转最新文章目录阅读
https://mp.weixin.qq.com/s/5jQspEvH5_4Xmart22gjMA



https://wap.sciencenet.cn/blog-3334560-1116994.html

上一篇:斯坦福大学统计系教授带你玩转微生物组分析
下一篇:一文读懂宏基因组分析套路
收藏 IP: 159.226.116.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...
扫一扫,分享此博文

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-5-1 06:00

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部