从我们
生信技能树
历年的几千个马拉松授课学员里面募集了一些优秀的创作者,某种意义来说是传承了我们生信技能树的知识整理和分享的思想!
今天的是三周合计15天的数据挖掘授课学员一点一滴整理的授课知识点笔记哦,还有互动练习题哈,欢迎大家点击文末的阅读原文去关注我们学员的公众号哦!
ggplot2的使用
1、语法
在ggplot2中我们只需要输入自己的数据(data),确定自己想要做什么样的图(geom_function),设置好对应的坐标(mappings)就可以做出一个基本的图了。
library(ggplot2)
ggplot(data = iris) +
geom_point(mapping = aes(x = Sepal.Length,
y = Species))
要进一步美化图就需要认识ggplot2的其他参数。
2、属性设置(颜色、大小、透明度、点的形状、线型等)
手动设置属性:
ggplot(data = iris) +
geom_point(mapping = aes(x = Sepal.Length,
y = Sepal.Width),
color = 'blue',
size = 8,
alpha = 0.8,
shape = 23,
fill = 'red')
在实际数据中,通常有多组数据,为了将它们区分出来,我们需要对不同组别的数据分别进行设置,这时候就需要用到一个叫mapping的参数。
mapping映射:
按照数据框中的某一列来定义图的某个属性。极大地方便我们对数据的美化和分组。
例如我们以物种为分组信息来设置图的颜色。
ggplot(data = iris) +
geom_point(mapping = aes(x = Sepal.Length,
y = Petal.Length,
color = Species))
除此之外,我们也可以根据自己的喜好来修改映射的具体颜色。
ggplot(data = iris) +
geom_point(mapping = aes(x = Sepal.Length,
y = Petal.Length,
color = Species),
shape = 18,
size = 8) +
scale_color_manual(values = c('blue', 'red', 'green'))
3、几何对象(图层)
几何对象(图层)叠加
局部设置:
只对当前的图层有效
ggplot(data = iris) +
geom_smooth(mapping = aes(x = Sepal.Length, y = Petal.Length)) +
geom_point(mapping = aes(x = Sepal.Length, y = Petal.Length))
全局设置:
对所有的图层都有效
ggplot(data = iris, mapping = aes(x = Sepal.Length, y = Petal.Length)) +
geom_smooth() +
geom_point()
4、ggplot位置参数
ggplot(data = iris, mapping = aes(x = Species,
y = Sepal.Width,
fill = Species)) +
geom_boxplot() +
geom_point()
图中的点和数据中的不符,在数据中有150个数据,所以在图中应该有150个点。但是在图中的点远没有那么多。因为有很多点都重叠了,才会显示几个点,在数据图里面这种情况是不允许的。这时候就需要添加位置参数position,或者使用函数jitter()。
ggplot(data = iris, mapping = aes(x = Species, y = Sepal.Width, color = Species))+
geom_boxplot()+
geom_point(position = 'jitter')
ggplot(data = iris, mapping = aes(x = Species, y = Sepal.Width, color = Species))+
geom_boxplot()+
geom_jitter()
5、坐标系
coord_flip() 坐标翻转。
ggplot(data = iris, mapping = aes(x = Species, y = Sepal.Width, color = Species))+
geom_boxplot() +
geom_jitter() +
coord_flip()
6、主题
theme_bw() :改主题,去掉灰色格子。除此之外,还有其他的主题,可先将theme_输入后按Tab显示可用的主题。
ggplot(data = iris, mapping = aes(x = Species, y = Sepal.Width, color = Species))+
geom_boxplot() +
geom_jitter() +
coord_flip() +
theme_replace()
ggpubr
ggpubr是基于
ggplot2
的可视化包,
用于绘制符合出版物要求的图形。
library(ggpubr)
p = ggboxplot(iris, x = 'Species', y = 'Sepal.Length',
color = 'Species', shape = 'Species',
add = 'jitter');p
ggpubr还有一个非常方便的功能,实现组间的显著性比较。
p = ggboxplot(iris, x = 'Species', y = 'Sepal.Length',
color = 'Species', shape = 'Species',
add = 'jitter')
group 'setosa', 'versicolor'),
c('setosa', 'virginica'),
c('versicolor', 'virginica'))
p + stat_compare_means(comparisons = group,
aes(label = after_stat(p.signif)))