DAY6 生信入门-R语言作图

图就是数据,数据就是图

常见可视化R包

1. 作图

  • base 略显陈旧 了解一下
  • ggplot2 中坚力量 学起来有点难
  • ggpubr 江湖救急 ggplot2简化和美化 褒贬不一

2. 拼图

  • par里的mfrow:给基础包画出的图拼图。mfrow:基础包拼图最好用的函数。
#基础包拼图
#基础包画出的图无法赋值
par(mfrow=c(1,2))
plot(1:100)
plot(100:1)

基础包-绘图函数

image.png

高级 低级绘图函数区别:能不能单独出一张图


image.png
plot(iris[,1],iris[,3],col = iris[,5]) 
text(6.5,4, labels = 'hello')
boxplot(iris[,1]~iris[,5])
dev.off()

ggplot2 语法

  1. 入门级绘图模板
  2. 映射-颜色、大小、透明度、形状
  3. 分面
  4. 几何对象
  5. 统计变换
  6. 位置调整
  7. 坐标系

1. 入门级模版

ggplot(data = <DATA>)+
<GEOM_FUNCTION>(mapping = aes(<MAPPINGS>))

ggplot(data = iris)+
  geom_point(mapping = aes(x = Sepal.Length,
                           y = Petal.Length)) #注意没有引号
image.png

2. 映射:按照数据框的某一列来定义图的某个属性

映射是专属ggplot的名词,表跟数据有关的属性设置


image
ggplot(data = iris)+
  geom_point(mapping = aes(x = Sepal.Length,
                           y = Petal.Length,
                           color = Species))
#默认颜色,红绿蓝
image.png

手动设置

与映射区分,跟数据本身无关


image.png
ggplot(data = mpg) +
geom_point(mapping = aes( x= displ, y= hwy), color = "blue")   

映射vs手动设置

image.png

映射实际参数是列名且不加引号

3. 分面

把一张图变成多个子图

ggplot(data = iris) + 
  geom_point(mapping = aes(x = Sepal.Length, y = Petal.Length)) + 
  facet_wrap(~ Species) 
# facet_wrap(~ Species) :根据某一列按纵坐标方向把一张大图分成n张小图,n和这一列有多少个取值有关系。
#这一列的要求:1.有重复值 2.取值数量有限
image.png

3. 双分面

test = iris
test$group = sample(letters[1:5],150,replace = T)#新增一列
ggplot(data = test) + 
  geom_point(mapping = aes(x = Sepal.Length, y = Petal.Length)) + 
  facet_grid(group ~ Species)

image.png

image.png

这些点满足的条件:group =a,Species=setosa

练习题

#练习6-1
# 示例数据:ggplot2中数据集mpg
# 1.分别以mpg的displ和hwy两列作为横纵坐标,画点图。
ggplot(mpg) +
  geom_point(aes(x = displ, y = hwy))
> mpg #查看mpg数据类型tibble,优化版的data frame,显示行列数,每列数据类型
# A tibble: 234 x 11
   manufacturer model   displ  year   cyl trans  drv     cty   hwy fl    class
   <chr>        <chr>   <dbl> <int> <int> <chr>  <chr> <int> <int> <chr> <chr>
 1 audi         a4        1.8  1999     4 auto(~ f        18    29 p     comp~
 2 audi         a4        1.8  1999     4 manua~ f        21    29 p     comp~
 3 audi         a4        2    2008     4 manua~ f        20    31 p     comp~
 4 audi         a4        2    2008     4 auto(~ f        21    30 p     comp~
 5 audi         a4        2.8  1999     6 auto(~ f        16    26 p     comp~
 6 audi         a4        2.8  1999     6 manua~ f        18    26 p     comp~
 7 audi         a4        3.1  2008     6 auto(~ f        18    27 p     comp~
 8 audi         a4 qua~   1.8  1999     4 manua~ 4        18    26 p     comp~
 9 audi         a4 qua~   1.8  1999     4 auto(~ 4        16    25 p     comp~
10 audi         a4 qua~   2    2008     4 manua~ 4        20    28 p     comp~
# ... with 224 more rows
# 2.尝试修改颜色或大小,从mpg数据框中任选可以用来分类的列。
ggplot(data = mpg)+
  geom_point(mapping = aes(x =displ,
                           y = hwy,
                           color=class))
#hwy 是数值列,连续型数据,颜色渐变。颜色越浅数值越大。
#class 取值独立,离散型数据,独立颜色。
image.png

image.png
# 3.根据class列来分面
ggplot(data = mpg) + 
  geom_point(mapping = aes(x = displ, y = hwy)) + 
  facet_wrap(~ class,ncol = 4) 
#和nrow = 2一樣
ggplot(data = mpg) + 
  geom_point(mapping = aes(x = displ, y = hwy)) + 
  facet_grid(class ~ .)
#按纵向分图
image.png

image.png
# 4.根据drv和cyl两个变量来分面
ggplot(mpg)+
  geom_point(aes(x= displ, y = hwy))+
  facet_grid(drv~cyl)
#facet_grid沒有nrow,ncol選項,永远方方正正

4. 几何对象

image

理解分组

ggplot(data = test) + 
  geom_smooth(mapping = aes(x = Sepal.Length, 
                          y = Petal.Length))

image.png

显式分组
一条趋势线分为三条趋势线

ggplot(data = test) + 
  geom_smooth(mapping = aes(x = Sepal.Length, 
                            y = Petal.Length,
                            group = Species)) 

image.png

隐式分组
颜色+分组,一条线分为三条线

ggplot(data = test) + 
  geom_smooth(mapping = aes(x = Sepal.Length, 
                          y = Petal.Length,
                          color = Species))  ### 会画出三条线

image.png

几何对象可以叠加

一个geom函数画出的所有东西就是一个几何对象

ggplot(data = test) + 
  geom_smooth(mapping = aes(x = Sepal.Length, 
                          y = Petal.Length))+
  geom_point(mapping = aes(x = Sepal.Length, 
                           y = Petal.Length)) #局部映射,只管当前函数画出的几何对象

ggplot(data = test,mapping = aes(x = Sepal.Length, y = Petal.Length))+
  geom_smooth()+ #括号要写,空着
  geom_point() #全局映射,少几次复制粘贴

image.png

映射分局部映射和全局映射
局部映射仅对当前图层有效,全局映射对所有图层有效
图层:geom_xx()画出的单个几何对象

练习题

# 1.尝试写出下图的代码
# 数据是iris
# X轴是Species
# y轴是Sepal.Width
# 图是箱线图
ggplot(data = iris,mapping = aes(x = Species,y = Sepal.Width,color = Species))+
  geom_boxplot()
#魔鬼操作:color,fill都设置,箱线的线消失,失去中位数
image.png
# 2\. 尝试在此图上叠加点图,
# 能发现什么问题?
ggplot(data = iris,mapping = aes(x = Species,y = Sepal.Width,color = Species))+
  geom_boxplot()+
  geom_point()
#图上点的数量不够50,点重合,无法分辨
#先写的图层被压在了下面
image.png
# 3.用下列代码作图,观察结果
ggplot(test,aes(x = Sepal.Length,y = Petal.Length,color = Species)) +
  geom_point()+
  geom_smooth(color = "black")
# 请问,当局部映射和全局映射冲突,以谁为准?
#局部映射
#smooth不能以连续型数据定义颜色
image.png
练习题反馈出来的问题
  • 当局部映射和全局映射冲突,以局部映射为准
  • 图层叠加与覆盖的问题
  • 点图重叠的问题
    <meta charset="utf-8">

5. 统计变换

library(ggplot2)
ggplot(data = diamonds) + #原始数据
  geom_bar(mapping = aes(x = cut)) #y是自己数的
#几何对象函数
image
ggplot(data = diamonds) + 
  stat_count(mapping = aes(x = cut))
#统计函数
image

统计变换使用场景

1. 不统计,数据直接做图

fre = as.data.frame(table(diamonds$cut))

ggplot(data = fre) +
  geom_bar(mapping = aes(x = Var1, y = Freq), stat = "identity")#加参,给出横纵坐标,不统计

image.png
image

2.count改为prop

ggplot(data = diamonds) + 
  geom_bar(mapping = aes(x = cut, y = ..prop.., group = 1))

image
ggplot(data = diamonds) + 
  geom_bar(mapping = aes(x = cut, y = ..prop..)) 
#不加group = 1,出问题,柱形高度全部相等
image.png

6.位置关系

抖动的点图

ggplot(data = mpg,mapping = aes(x = class, 
                                y = hwy,
                                group = class)) + 
  geom_boxplot()+
  geom_point()

不对
ggplot(data = mpg,mapping = aes(x = class, 
                                y = hwy,
                                group = class)) + 
  geom_boxplot()+
  geom_jitter()
#正确的,横坐标位置范围扩大
# 注意:这里是换函数,把geom_point换成geom_jitter,而不是加函数
正确的箱线图上叠加点图

堆叠直方图 默认

ggplot(data = diamonds) + 
  geom_bar(mapping = aes(x = cut,fill=clarity))

image

并列直方图

ggplot(data = diamonds) + 
  geom_bar(mapping = aes(x = cut, fill = clarity), position = "dodge")
#加position参数
image

7. 坐标系

1. 翻转坐标系 coord_flip()
ggplot(data = mpg, mapping = aes(x = class, y = hwy)) + 
  geom_boxplot() +
  coord_flip()
#注意:这里是加函数
image
2. 极坐标系coord_polar()
bar <- ggplot(data = diamonds) + 
  geom_bar(
    mapping = aes(x = cut, fill = cut), 
    show.legend = FALSE,
    width = 1
  ) + 
  theme(aspect.ratio = 1) +
  labs(x = NULL, y = NULL)
bar + coord_flip()

image
bar + coord_polar()

image

完整绘图模板

图层之间可以使用不同数据


image.png

练习6-3

test=iris
ggplot(data = test, mapping = aes(x = Species, y = Sepal.Width)) + 
 geom_violin(aes(fill=Species))+
 geom_boxplot() +
 geom_jitter(mapping = aes(shape=Species))+  
 coord_flip()
ggsave("practice6-3.png") 

image

ggpubr

ggpubr 搜代码直接用,基本不需要系统学习
sthda上有大量ggpubr出的图

library(ggpubr)
ggscatter(iris,x="Sepal.Length",y="Petal.Length",color="Species")
#区别:ggscatter相当于ggplot+geom_;加引号;图例正上方;去掉了灰色背景
#ggplot加参数也可以达到一样的效果
ggplot(iris,aes(x = Sepal.Length,y = Petal.Length,color = Species)) +
  geom_point()+
  theme_classic()+
  theme(legend.position = "top")
image
p <- ggboxplot(iris, x = "Species", y = "Sepal.Length",
          color = "Species", shape = "Species",
          add = "jitter")
p
#赋值,给图命名一般用P1,P2
image
my_comparisons <- list( c("setosa", "versicolor"), c("setosa", "virginica"), c("versicolor", "virginica") )
#组成的是:长度为2的向量组成的列表
p + stat_compare_means(comparisons = my_comparisons)+ # 组间比较,最不可替换
  stat_compare_means(label.y = 9) 
#可以用+添加,和ggplot一样
#多句代码用+连接,表示在画同一张图
#控制台开头的+,表示一行代码未完
image

图片保存

1. ggplot系列图(包括ggpubr)通用的简便保存 ggsave

ggsave

ggsave("iris_box_ggpubr.png")

#前提:画板清空;p已赋值
ggsave(p,filename = "iris_box_ggpubr2.png")
#在不显示图的基础上,保存图

2. 通用:三段论

先新建PDF,再一步步画图


image.png
#通用保存
pdf("iris_box_ggpubr.pdf")
boxplot(iris[,1]~iris[,5])
text(6.5,4, labels = 'hello')
dev.off()

3. eoffice包 导出为ppt,全部元素都是可编辑模式

library(eoffice)
topptx(p,"iris_box_ggpubr.pptx") #注意写x
#出问题的话,就换rio包里的export,导出为PPT
#PPT取消组合,就变为多个可移动的对象

拼图

image.png
library(patchwork)
x=ggplot(data = mpg, mapping = aes(x = class, y = hwy)) + 
  geom_boxplot() +
  coord_flip()
p1=bar + coord_flip()
p2=bar + coord_polar()
p1+p2+bar+x
image.png
p1+p2+bar+x & theme_bw() #取消灰色背景,&应用所有图形
image.png
p1+p2+bar+x + plot_annotation(tag_levels = "A") #给图片加ABCD
image.png
#收集图例,其他拼图R包都做不了
p1+p2+bar+x + plot_layout(guides="collect")
#一样的图例就整理成一个
image.png
练习题 6-4
# 2\. 尝试使用labs()
ggplot(mtcars, aes(mpg, wt, colour = cyl)) + 
  geom_point()+
  labs(title = "This is a title",subtitle = "This is a subtitle",caption = "This is a caption")+ #设置图片标题、子标题、引用
  labs(x = "New x label")+
  labs(y = "New y label")+ #修改x轴y轴标题
  labs(title = "title", tag = "A")+ #加tag
  labs(title = NULL)+
  labs(tag = NULL) #取消用NULL
image.png
# 3\. 如何在保存的同时调整比例
ggsave("x.png",width = 10,height = 10) #用width,height调整比例
image.png

代码可运行却不出图-因为画板被占用

  1. dev.off(), 表示关闭画板。多次运行,到null device 为止。再运行出图代码。


    image.png

2.还不行,dev.new(),新建一个画板,运行代码

  1. 还不行,重启session, Rstudio,电脑

分享一个做美图的网站

http://www.sthda.com/english/

画图合辑

https://www.jianshu.com/nb/35523479

image.png

美图代码+你的数据+你解决问题的能力=你的图
难点不是作图代码,而是如何将你的数据整理成示例数据的样子

作者:Ruizheng
链接:https://www.jianshu.com/p/a3fc06784f6c
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容