ggjoy facet 与 ggtree

ggjoy facet with ggtree

是否可以将 joyplot 作为面板添加到包含 ggtree 的绘图中,如 these examples? Examples of joyplots are here 所示。

我知道我可以手动将 joyplot 的物种标签按照与树尖标签相同的顺序放置,但我正在寻找一种自动解决方案。我想自动将 joyplot 行与树的提示相关联,类似于箱线图数据与提示标签的关联方式。

我觉得上面余光创的例子link提供了合适的数据:

require(ggtree)
require(ggstance)

# generate tree
tr <- rtree(30)

# create simple ggtree object with tip labels
p <- ggtree(tr) + geom_tiplab(offset = 0.02)

# Generate categorical data for each "species"
d1 <- data.frame(id=tr$tip.label, location=sample(c("GZ", "HK", "CZ"), 30, replace=TRUE))

#Plot the categorical data as colored points on the tree tips
p1 <- p %<+% d1 + geom_tippoint(aes(color=location))

# Generate distribution of points for each species
d4 = data.frame(id=rep(tr$tip.label, each=20), 
            val=as.vector(sapply(1:30, function(i) 
                            rnorm(20, mean=i)))
            )               

# Create panel with boxplot of the d4 data
p4 <- facet_plot(p1, panel="Boxplot", data=d4, geom_boxploth, 
        mapping = aes(x=val, group=label, color=location))           
plot(p4)

这会产生下面的图:

是否可以创建一个欢乐图来代替箱线图?

下面是上面演示数据集 d4 的快速 joyplot 代码:

require(ggjoy)

ggplot(d4, aes(x = val, y = id)) + 
geom_joy(scale = 2, rel_min_height=0.03) + 
scale_y_discrete(expand = c(0.01, 0)) + theme_joy()

结果是:

我是 ggplot2、ggtree 和 ggjoy 的新手,所以我完全不知道如何开始这样做。

注:截至 2017-09-14,ggjoy package has been deprecated. Instead, use the ggridges package。要使下面的代码与 ggridges 一起使用,请使用 geom_density_ridges 而不是 geom_joy.


看来您可以将 facet_plot 中的 geom_boxplot 替换为 geom_joy:

facet_plot(p1, panel="Joy Plot", data=d4, geom_joy, 
           mapping = aes(x=val, group=label, fill=location), colour="grey50", lwd=0.3) 

如果您是 ggplot2 的新手,the visualization chapter of Data Science with R(ggplot2 作者的开源书籍)应该有助于学习基础知识。

ggjoyggtree 扩展了 ggplot2 的功能。当这样的扩展做得很好时,"obvious" 要做的事情(就通常的 ggplot "grammar of graphics" 而言)通常会起作用,因为扩展包是以一种试图忠实于底层 ggplot2 的方式编写的方法。

在这里,我的第一个想法是将 geom_joy 替换为 geom_boxplot,结果证明可以完成工作。每个 geom 只是一种可视化数据的不同方式,在本例中为箱线图与密度图。但是绘图的所有其他 "structure" 都保持不变,因此您只需更改几何图形并获得遵循相同轴顺序、颜色映射等的新绘图。一旦您获得一些经验,这将更有意义与图形的ggplot2语法。

左侧图的标记方法略有不同:

p1 = ggtree(tr) %<+% d1 +
  geom_tippoint(aes(color=location), size=6) +
  geom_tiplab(offset=-0.01, hjust=0.5, colour="white", size=3.2, fontface="bold") 

facet_plot(p1, panel="Joy Plot", data=d4, geom_joy, 
           mapping = aes(x=val, group=label, fill=location), colour="grey40", lwd=0.3) 

更新: 这是对您询问如何在两个面板中获得相同自定义颜色的评论的回应。这是使用问题中的示例数据执行此操作的代码:

p1 = ggtree(tr) %<+% d1 +
  geom_tippoint(aes(color=location), size=5) +
  geom_tiplab(offset=-0.01, hjust=0.5, colour="white", size=3, fontface="bold") +
  scale_colour_manual(values = c("grey", "red3", "blue")) +
  scale_fill_manual(values = c("grey", "red3", "blue"))

facet_plot(p1, panel="Joy Plot", data=d4, geom_joy, 
           mapping = aes(x=val, group=label, fill=location), colour="grey40", lwd=0.3)