结合两个ggplots而不会干扰美学

时间:2016-05-06 02:37:53

标签: r ggplot2

情节1:

g1 = ggplot(path[order(path$order),], aes(PC1, PC2)) + geom_point(aes(color=position, size=path_size)) + 
geom_text(aes(label=order, vjust=2)) + geom_path() + xlim(0,0.03) + ylim(-0.03,0.03)

enter image description here

理想情况下,我希望将路径的START和END位置设置为不同的颜色/形状/大小,以使其看起来与众不同。

情节2:

g2 = ggplot(d, (aes(x=PC1, y=PC2, color=CellType))) + geom_point() 

enter image description here

图1是通过图2中的点子集的有向路径。我不确定如何在不干扰美学的情况下组合这两个图。剪切用于生成每个图的数据如下所示:

path = d[as.vector(colnames(adj)), 1:2]
path$order = seq(1:nrow(path))
path$position = as.factor(ifelse(path$order == 1, "START", ifelse(path$order == nrow(path), "END", "PATH")))
path_size = as.factor(ifelse(path$order == 1, 2, ifelse(path$order == nrow(path), 2, 1)))



> head(path)
                                     PC1        PC2 order position
D6_NoSort2250b_TGTCCCCCACTC   0.02303190 0.01264362     1    START
D6_NoSort6000b_TTCTTTAACCCC   0.01054032 0.02401583     2     PATH
D6_EcadSort2250b_ACGGTTTGGCTT 0.01548174 0.02315813     3     PATH
D6_EcadSort2250b_CAGCCCGCTATT 0.02263683 0.01523706     4     PATH
D6_NoSort2250b_GACAGCACGTCT   0.02262139 0.01252870     5     PATH
D6_NoSort2250b_CCAGCACGGTAA   0.01986103 0.01584703     6     PATH

> head(d[,1:2])
                                    PC1         PC2
MEF_23x2cycGelX_ACCTAAGTTACC 0.01394239 0.003256282
MEF_18cycGelX_TGGACTATCTAG   0.01368773 0.009878876
MEF_18cycGelX_GGATACCCGCTT   0.01423563 0.010897071
MEF_18cycGelX_CTTTCAGCGCTC   0.01315417 0.012731415
MEF_18x2cycGelX_GCAGGTTCATTT 0.01318875 0.013687629
MEF_18cycGelX_CTTTCGTCCTGC   0.01102215 0.013257857

非常感谢任何帮助。

编辑:更新了代码

1 个答案:

答案 0 :(得分:2)

这是一个组合两个图的想法,这将产生如下所示的图。基本上,关键是在geom_point函数中单独指定非路径图的数据。另外,我在路径点添加了一个形状参数,以实现路径的START和END位置不同...形状"

library(ggplot2)
path <- data.frame(PC1=c(0.02303190,0.01054032,0.01548174,0.02263683,0.02262139,0.01986103),
                   PC2=c(0.01264362,0.02401583,0.02315813,0.01523706,0.01252870,0.01584703),
                   order=c(1,2,3,4,5,6))
path$color = as.factor(ifelse(path$order == 1, "START", ifelse(path$order == nrow(path), "END", "PATH")))

d <- data.frame(PC1=c(0.01394239,0.01368773,0.01423563,0.01315417,0.01318875,0.01102215),
                PC2=c(0.003256282,0.009878876,0.010897071,0.012731415,0.013687629,0.013257857),
                cellType=c("D6", "ESC", "MEF", "D6", "ESC", "MEF"))


g2 = ggplot(path[order(path$order),], aes(PC1, PC2)) + 
  geom_point(data=d, aes(x=PC1, y=PC2, color=cellType)) +
  geom_point(aes(PC1, PC2, shape=color), color="black") + 
  geom_text(aes(label=order, vjust=2)) + geom_path()
g2

enter image description here