I would really appreciate some help solving this issue with ggplot/ggplotly in R
I’m trying to feed into ggplotly() a ggplot made with autoplot(), specifically, a PCA.
The goal I have is for plotly to display the row names of each data entry for the PCA. For example, when plotting the PCA and using colour=”Species” for the iris data set, the resulting ggplotly PCA only shows the colored groups and PC1/PC2 values (example below):
library(ggfortify)
library(plotly)
df = iris[1:4]
pca_res <- prcomp(df, scale. = TRUE)
pca_plot = autoplot(pca_res, data = iris, colour = 'Species') +
theme_bw()
ggplotly(pca_plot)
produces:
Plotly PCA
I’m trying to find a way to include the row names when hovering over a point on the PCA from the data = iris data frame (shown below):
Iris dataframe rownames
So when hovering over a data point, it would show the corresponding row name for the data entry which generated the point (i.e., a point would be labeled “1”, “2”, “3”, … in this case), without having any additional legend details
I’ve tried adding labels using an additional geom and specifying label = TRUE in the autopilot, but the labels are persistent; the solution I’m looking for would only display the row names when hovering over the points. This is what I’ve tried:
pca_plot = autoplot(pca_res, data = iris, colour = 'Species', label=FALSE) +
theme_bw()
ggplotly(pca_plot, tooltip="label")
and
pca_plot = autoplot(pca_res, data = iris, colour = 'Species', label = TRUE) +
theme_bw()
ggplotly(pca_plot, tooltip="label")
and
pca_plot = autoplot(pca_res, data = iris, colour = 'Species') +
geom_label(label = row.names(iris))
theme_bw()
ggplotly(pca_plot)
Tech.learner is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.