Unable to plot hclust object with ggtree - r

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 really see what is wrong...

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 beeing 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')
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')

Related

Ordination Graph in R

Before I begin, I am very much a beginner at R, so apologies if this is an easy fix.
I need to create an ordination graph with species labels and a key. I found the 'vegan' package which I believe is relevant. I've read in the table and attached it and also have loaded the package:
Ordination<-read.table("pHWTD.txt", header = T, stringsAsFactors = T)
attach(Ordination)
library(vegan)
ordiplot(Mean_pH ~ Mean_Water_Table_Depth)
After this ordiplot function, the console returns: "Error in NROW(X) : object 'X' not found"
I don't understand this because Mean_pH and Mean_Water_Table_Depth are variables, so unsure what is not being found.
Below is a generalised version of the data I need to plot (where each species will be represented by a graphical point with an abbreviated label e.g. Species 1 could be spec.1):
Any advice, if possible, would be appreciated.
Many thanks in advance.

Why graphics::plot call on hexbin object throws an error?

In short: I'm trying to run this hexbin example which works fine unless I replace plot with graphics::plot. The latter throws following error:
> graphics::plot(bin, main="" , colramp=my_colors , legend=F )
Error in as.double(y) :
cannot coerce type 'S4' to vector of type 'double'
How to make this work?
Wider context why I need this work this way. I contribute to the clojisr project which brings R to Clojure using RServe. There is an option to require R packages and create corresponding Clojure functions. This works well (see this or this). The underlying calls to R are in the form of {package::symbol} for everything.
Class hexbin is an S4 class and the package defines an S4 generic and a method for plot. (The source code is here). There is no S4 generic for plot in the graphics package namespace, only an S3 generic.
The solution is therefore very simple:
hexbin::plot(bin, main="" , colramp=my_colors , legend=F )
Here's a reprex to prove it:
library(hexbin)
library(RColorBrewer)
# Create data
x <- rnorm(mean=1.5, 5000)
y <- rnorm(mean=1.6, 5000)
# Make the plot
bin<-hexbin(x, y, xbins=40)
my_colors=colorRampPalette(rev(brewer.pal(11,'Spectral')))
hexbin::plot(bin, main="" , colramp=my_colors , legend=F )
Created on 2020-02-17 by the reprex package (v0.3.0)

Using pcaCoda from the package "robCompositions" with ggplot2

I would like to plot the results of the robust PCA (pcaCoDa) from the robCompositions package using ggplot2.
Previously, it worked with ggbiplot (https://github.com/vqv/ggbiplot) however, I can no longer get it to work with my current R version (3.6.0).
Is there a way to do a biplot with the pcaCoda results with ggplot2 using CRAN packages?
Here is a working example without using ggplot:
library(robCompositions)
df <- arcticLake
a <- pcaCoDa(df)
biplot(a)
And another example without using the robust PCA, but using the autoplot function:
library(ggplot2)
autoplot(princomp(df))
However, I would like to use the robust PCA with ggplot/autoplot. When I try to plot it, i get the following error:
autoplot(a)
Error: Objects of type pcaCoDa not supported by autoplot.
I also tried the following and also get an error:
autoplot(a$princompOutputClr)
Error in scale.default(data, center = FALSE, scale = 1/scale) :
length of 'scale' must equal the number of columns of 'x'
Any advice? Thanks!
For some reasons that I ignore pcaCoda returns one value less for scale and center compared to the output of other pca methods such as prcomp or princomp. I think that's the reason why autoplot does not want to plot this object.
Alternatively, if you want to apply the robust algortithm, you can use the package pcaMethods available on bioconductor, here i provided an example using the iris dataset that you can found on the documentation of pcaMethods (https://bioconductor.org/packages/release/bioc/html/pcaMethods.html):
if (!requireNamespace("BiocManager", quietly = TRUE))
install.packages("BiocManager")
BiocManager::install("pcaMethods")
library(pcaMethods)
library(ggplot2)
robust = pca(iris[c(1, 2, 3, 4)], method = "robustPca", scale = "uv", center = TRUE)
iris = merge(iris, scores(robust), by =0)
ggplot(iris, aes( x= PC1, y = PC2, colour = Species))+
geom_point()+
stat_ellipse()
Does it look what you are trying to get ?

ggplot error: 'names' attribute [2] must be the same length as the vector [1]

I wanna use PCA but I can not plot it! I run PCA successfully using packege and following code:
pc<-prcomp(C, scale = FALSE)
summary(pc)
then for plot I used
library(devtools)
install_github("vqv/ggbiplot")
library(ggbiplot)
ggbiplot(pc)
But I get this error:
Error in names(df.v) <- names(df.u) :
'names' attribute [2] must be the same length as the vector [1]
I typically use ggplot for my PCA plotting needs, as it allows me to overlay metadata by color/shape coding.
My typical code for a basic PCA is just:
library(ggfortify)
library(ggrepel)
library(GGally)
library(gplots)
library(ggplot2)
x <- prcomp(y)
autoplot(x) + #any color/shape/text edits you want to make
This code was passed down to me by someone I work with, but I've not had any issues with it.

autoplot does not accept ts object

I am creating a ts object and then I am trying to run it through autoplot. Execution gives me an error:
autoplot(pts, facets = TRUE)
Error: Objects of type mts/ts/matrix not supported by autoplot.
I have already checked the type of the object , and it is ts and autoplot is supposed to make a plot out of the ts object. I also tried to run other built in ts object (USAccDeaths) , but it gives me same error
library(ggplot2)
pts <- ts(data = Popcopys[,-1], start = c(2006,1),frequency = 1 )
autoplot(pts)
autoplot(USAccDeaths)
A plot of TS is expected , but what I get is this error:
autoplot(pts)
Error: Objects of type mts/ts/matrix not supported by autoplot.
autoplot(USAccDeaths)
Error: Objects of type ts not supported by autoplot.
This works:
library(ggplot2)
library(ggfortify)
autoplot(USAccDeaths)
Following https://cran.r-project.org/web/packages/ggfortify/vignettes/plot_ts.html :
"{ggfortify} lets {ggplot2} know how to interpret ts objects"
If you have ggplot or tidyverse loaded into your environment along with the forecast library both have an autoplot function.
You will need to specify which you are attempting to use.
library(forecast)
library(ggplot2)
data <-read.csv('C:/users/person/desktop/data.csv')
ts_df <-ts(data, start = 2018, frequency = 52)
forecast::autoplot(ts_df[,'Column_name'])

Resources