rhclustggtree

Unable to plot hclust object with ggtree


I am trying to plot a dendrogram from a hclust object with ggtree but I keep getting the same error message:

Error: `data` must be a data frame, or other object coercible by `fortify()`, not an S3 object with class hclust

I have been extensively looking for a solution, but found none. Furthermore, I have learned that ggtree does support hclust objects, which has confused me even more. From here:

The ggtree package supports most of the hierarchical clustering objects defined in the R community, including hclust and dendrogram as well as agnes, diana and twins that defined in the cluster package.

I have borrowed a reproducible example from the link above:

hc <- hclust(dist(mtcars))
p <- ggtree(hc, linetype='dashed')

Which, again, gives me the abovementioned error. If I use rlang::last_error() to get a bit of context, I get:

<error/rlang_error>
`data` must be a data frame, or other object coercible by `fortify()`, not an S3 object with class hclust
Backtrace:
 1. ggtree::ggtree(hc, linetype = "dashed")
 3. ggplot2:::ggplot.default(...)
 5. ggplot2:::fortify.default(data, ...)

And if I use rlang::last_trace() to get a bit further information:

<error/rlang_error>
`data` must be a data frame, or other object coercible by `fortify()`, not an S3 object with class hclust
Backtrace:
    x
 1. \-ggtree::ggtree(hc, linetype = "dashed")
 2.   +-ggplot2::ggplot(...)
 3.   \-ggplot2:::ggplot.default(...)
 4.     +-ggplot2::fortify(data, ...)
 5.     \-ggplot2:::fortify.default(data, ...)

But I can't really see what is wrong...


Solution

  • I have managed to solve my issue. I will post it in case it is of help for someone else in the future.

    Apparently, I was running an older version of ggtree which was not being correctly updated when I reinstalled ggtree from Bioconductor, I am not sure why. Anyway, I tried to reinstall it by explicitly setting the version argument in the installation call:

    BiocManager::install("ggtree", version = "3.10")
    

    And then I could successfully run my reproducible example:

    hc <- hclust(dist(mtcars))
    p <- ggtree(hc, linetype='dashed')
    

    enter image description here

    Note that as a previous workaround, I had managed to plot the hcluster object with ggtree by transforming it to a phylo object with the as.phylo() function from the ape package:

    hc <- hclust(dist(mtcars))
    hc <- ape::as.phylo(hc)
    p <- ggtree(hc, linetype='dashed')