Search code examples
rggplot2plotlyautoplot

Autoplot(ly): how can labels appear when hovering over points


I am trying to figure out how to label the points in a graph such that the label appears only when hovering over the point but not otherwise.

Consider the following reproducible example:

library(ggfortify)
library(ggplot2)
library(autoplotly)
d <- iris
d$indexLabel <- 1:nrow(d)
pca_res <- prcomp(d[, 1:4], scale = TRUE)
g<-autoplot(pca_res,
  data = iris, colour = "Species"
)
autoplotly(g)

I would like the indexLabel variable to appear ONLY when hovering over each dot. How do I do that? I have tried several things unsuccessfully. I am trying to do it with autoplotly but if there are other ways please let me know.


Solution

  • I would construct the plot myself, as you have much finer control of what is plotted where. To get you started, I reconstructed the autoplot with just a couple of lines (colors and background could be changed as well if needed) and added the indexLabel as additional info to the hoverbox.

    You have fulkl control of what you want to place in the hoverbox via the hovertemplate argument which you can freely adapt your needs.

    ## first fortify your data to have data and results conveniently in one data.frame
    full_data <- fortify(pca_res, d) 
    ## calculate percentages for the PCs
    perc <- pca_res$sdev ^ 2 / sum(pca_res$sdev ^ 2)
    
    ## create plot from scratch
    plot_ly(full_data) %>% 
      add_markers(
        x = ~ PC1,
        y = ~ PC2,
        color = ~ Species,
        customdata = ~ Species,
        text = ~ indexLabel,
        hovertemplate = "PC1: %{x:.3r}<br>PC2: %{y:.3r}<br>Index:%{text}<br>Species: %{customdata}"
      ) %>% 
      layout(
        xaxis = list(zeroline = FALSE, 
                     title = paste0("PC1 (", round(perc[1] * 100, 2L),"%)")),
        yaxis = list(zeroline = FALSE, 
                     title = paste0("PC2 (", round(perc[2] * 100, 2L),"%)"))
        )
    

    This produces the following plot (tooltip is shown only on hover but included in this screenshot to show the info):

    A scatterplot with 3 colors showing the principal components of the PCA of hte iris data set. The color represent the differnt species. A tooltip is showing on hovering giving the coordinates as well as some additional info as requested.