【问题标题】:Create a circular phylogeny with stacked bar in R在 R 中创建一个带有堆叠条的圆形系统发育
【发布时间】:2021-11-12 13:28:45
【问题描述】:

我正在尝试在每个树尖的末端创建一个带有堆积条形图的循环系统发育。以下是我微弱尝试的一些示例代码和数据。我可以创建圆形系统发育以及堆叠条形图,但我似乎无法将树尖链接到条形图中的 x 轴。

我发现此站点上的一些代码很有用,但我仍然无法正确拼凑:https://www.r-graph-gallery.com/299-circular-stacked-barplot.html

我添加了更详细的示例数据:

#An example of my newick tree file:
(((((species1,species2),species3),species4),((species5,species6),species7)),species8)

#An example of my data file:
SPECIES     CATEGORY     VALUES
species1    A            5
species1    B            10
species1    C            15
species2    A            2
species2    B            8
species2    C            4
species3    A            8
species3    B            5
species3    C            3
species4    A            6
species4    B            5
species4    C            11
species5    A            14
species5    B            5
species5    C            13
species6    A            3
species6    B            4
species6    C            1
species7    A            7
species7    B            9
species7    C            5
species8    A            10
species8    B            4
species8    C            12

ggtree(my_tree, layout='circular') %<+% category_data + ggplot(category_data) + geom_bar(aes(x=as.factor(category_data$SPECIES), y=category_data$VALUES, fill=category_data$CATEGORY), stat="identity", alpha=0.5) + scale_fill_viridis(discrete=TRUE)

【问题讨论】:

    标签: r ggplot2 geom-bar phylogeny ggtree


    【解决方案1】:

    在笛卡尔坐标中调试极坐标图通常是最容易的。由于示例数据不足以重现问题,因此我使用标准数据集进行了一些即兴创作。

    首先,我们将对mtcars 数据进行聚类,并将汽车名称与聚类中的标签进行匹配。

    library(ggplot2)
    library(ggdendro)
    #> Warning: package 'ggdendro' was built under R version 4.1.1
    
    tree <- hclust(dist(mtcars))
    tree <- dendro_data(tree)
    
    data <- cbind(mtcars, x = match(rownames(mtcars), tree$labels$label))
    

    接下来,我们将在条形图下方绘制树状图。我们将确保叶子在顶部,并且树状图与条形图成一定比例。

    scale <- 0.1
    p <- ggplot() +
      geom_col(
        data = tidyr::pivot_longer(data, c(drat, wt, qsec)),
        aes(x = x,
            y = value, fill = factor(name))
      ) +
      geom_segment(
        data = tree$segments,
        aes(x = x, y = -y * scale, xend = xend, yend = -yend * scale)
      )
    
    p
    

    最后,我们只需要添加极坐标。

    p + coord_polar()
    

    reprex package (v2.0.1) 于 2021-09-17 创建

    【讨论】:

    • 我还有一些问题。我的树是 phylo 对象(来自 .newick 文件)而不是树状图,这会导致此行出现错误: data = tree$segments, aes(x = x, y = -y * scale, xend = xend, yend = -yend * scale)) >>> FUN 中的错误(X[[i]],...):找不到对象“x”。我已经考虑将我的 phylo 对象转换为 dendro 对象,但我似乎无法使其工作。我已经更新了原始问题中的示例数据,希望能增加一些清晰度。
    • 我对那种特定的文件格式一无所知。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-06
    • 2021-07-31
    • 1970-01-01
    • 1970-01-01
    • 2013-09-09
    • 2021-11-16
    • 2012-03-14
    相关资源
    最近更新 更多