微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 ggplot facet 中添加表格

如何解决在 ggplot facet 中添加表格

我需要帮助才能在我的图中添加 geom_table 之类的东西。

这是我可以生成的图:

enter image description here

这是我使用的代码

library(ggtree)
library(ggplot2)
library(ggstance)

tr <- rtree(30)
p <- ggtree(tr)
#df1<-dput(read.table("/Users/user/Desktop/test_data.txt",sep=";",h=T))
p1 <- p %<+% df1 + geom_tippoint(aes(color=location))
d2 <- data.frame(id=tr$tip.label,val=rnorm(30,sd=3))
p2 <- facet_plot(p1,panel="dot",data=d2,geom=geom_point,aes(x=val),color='firebrick') + theme_tree2()
d3 <- data.frame(id = rep(tr$tip.label,each=2),value = abs(rnorm(60,mean=100,sd=50)),category = rep(LETTERS[1:2],30))
p3 <- facet_plot(p2,panel = 'Stacked Barplot',data = d3,geom = geom_barh,mapping = aes(x = value,fill = as.factor(category)),stat='identity' ) 

我想知道是否有办法在 df1$Value 旁边添加带有 Tree facet 的表格?如:

enter image description here

df1 数据:

structure(list(id = structure(c(5L,15L,29L,18L,24L,21L,13L,11L,8L,25L,23L,9L,16L,3L,6L,2L,20L,27L,30L,17L,14L,4L,1L,7L,22L,28L,10L,12L,26L,19L),.Label = c("t1","t10","t11","t12","t13","t14","t15","t16","t17","t18","t19","t2","t20","t21","t22","t23","t24","t25","t26","t27","t28","t29","t3","t30","t4","t5","t6","t7","t8","t9"),class = "factor"),location = structure(c(1L,1L),.Label = c("CZ","GZ","HK"),Value = c(NA,NA,45L,89L,80L,NA)),class = "data.frame",row.names = c(NA,-30L))

解决方法

我不熟悉 ggtree 包或其语法,但一些试验和错误表明您可以简单地使用 geom_textgeom_bar 进行扩展以获得类似表格的方面。

library(ggtree)
library(ggplot2)
library(ggstance)

df1 <- structure(
  list(id = structure(
    c(5L,15L,29L,18L,24L,21L,13L,11L,8L,25L,23L,9L,16L,3L,6L,2L,20L,27L,30L,17L,14L,4L,1L,7L,22L,28L,10L,12L,26L,19L),.Label = c("t1","t10","t11","t12","t13","t14","t15","t16","t17","t18","t19","t2","t20","t21","t22","t23","t24","t25","t26","t27","t28","t29","t3","t30","t4","t5","t6","t7","t8","t9"),class = "factor"),location = structure(c(1L,1L),.Label = c("CZ","GZ","HK"),Value = c(NA,NA,45L,89L,80L,NA)),class = "data.frame",row.names = c(NA,-30L))

tr <- rtree(30)
p <- ggtree(tr)
#df1<- your_example_data
p1 <- p %<+% df1 + geom_tippoint(aes(color=location))
d2 <- data.frame(id=tr$tip.label,val=rnorm(30,sd=3))

# Here be the extra bits
p11 <- facet_plot(p1,panel = "new_facet",geom = geom_tile,aes(x = 0),fill = NA,colour = "black",data = df1)
p12 <- facet_plot(p11,geom = geom_text,aes(x = 0,label = df1$Value),data = df1)

# Note p12 goes into p2
p2 <- facet_plot(p12,panel="dot",data=d2,geom=geom_point,aes(x=val),color='firebrick') + theme_tree2()
d3 <- data.frame(id = rep(tr$tip.label,each=2),value = abs(rnorm(60,mean=100,sd=50)),category = rep(LETTERS[1:2],30))
p3 <- facet_plot(p2,panel = 'Stacked Barplot',data = d3,geom = geom_barh,mapping = aes(x = value,fill = as.factor(category)),stat='identity' )
p3
#> Warning: Removed 25 rows containing missing values (geom_text).

reprex package (v1.0.0) 于 2021 年 2 月 16 日创建

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。