图一般都是静止的,R语言里面有很方便的工具让他们动起来。
这个R包叫gganimate
,他的作用就是让ggplot2画出来的图以某个因素,比如时间,动起来。

时间在流逝,数据在变化,由于时间点太多,静止的图片表现力度比较差,换成动图表现力好很多。
如果我们看到一张图比较炫酷,首先想到的应该是,我有什么数据能用这种方式来展示,说到底,还是自己手上要有数据。我想了一下,没有。
没有就造一个,我们有癌症的数据,多个亚型,多个基因,也许能尝试一下。手上的数据是这样的:

他有四列,分别是亚型,样本类别,基因名你,表达量。这是清洁数据,可以方便的用ggplot2画图。
library(ggplot2)
ggplot(test,aes(x=subgroup,y=expression,fill=subgroup))+
geom_boxplot()+
geom_jitter()+
theme_bw()

这是这四个基因,实际上我们可以添加一个分面,让他表示四个基因不同的表达量。
library(ggplot2)
p <- ggplot(test,aes(x=subgroup,y=expression,fill=subgroup))+
geom_boxplot()+
geom_jitter()+
theme_bw()
p +facet_grid(.~gene)

但是因为空间比较狭窄,并没有很好的效果。尝试用动图来展示一下,
gganimate
中的transition_***
功能使用方式跟facet_grid
分面差不多,就是先分面,再以动图依次显示。transition_***
函数有好几个:
如果是时间就选择
transition_time()
,我们这里是分类数据,选择transition_states()
library(ggplot2)
library(gganimate)
p <- ggplot(test,aes(x=subgroup,y=expression,fill=subgroup))+
geom_boxplot()+
geom_jitter()+
theme_bw()
p +transition_states(gene,
state_length = 0)+
labs(title = "{closest_state} expression(TPM)")

这个图会依次呈现各个基因在每个亚型中的表达,确实实现了动图的功能,我觉得没什么大的作用,因为没有人会这么展示数据。我又尝试了一下可以用亚型来作为转换变量,依次显示每个亚型的中四个基因的表达变化。
library(ggplot2)
library(gganimate)
p <- ggplot(test,aes(x=gene,y=expression))+
geom_boxplot(aes(color=gene),size=2)+
geom_jitter()+
theme_bw()
p +transition_states(subgroup,
transition_length = 0.1,
state_length = 0)+
labs(title = "{closest_state}")

好像有点作用,ESR1和FOXA1这两个基因在不同亚型中变化比较大,如果了解乳腺癌的背景知识就会明白这个符合事实的。不过,说实话,我还是觉得手上没有合适的数据,最好的数据是时间,比如你有过去很多年的临床数据,答辩的时候我觉得可以考虑一下这个方法。
最后,把这个边框给去掉了,就实现了基因放烟花的功能
library(ggplot2)
library(gganimate)
p <- ggplot(test,aes(x=gene,y=expression,color=gene))+
#geom_boxplot()+
geom_jitter()+
theme_bw()
p +transition_states(subgroup,
transition_length = 0.1,
state_length = 0)+
labs(title = "{closest_state}")

如果你想重复这个练习,可以在"果子学生信"公众号回复“烟花”自助获取一开始的那个数据。
我是果子,明天见。
网友评论