Search code examples
rggplot2tooltippcar-plotly

tooltip with names in a PCA plot


I want to generate an interactive plot with ggplotly(). The tooltip should show me the name of the variable.

interactive <- ggplotly(pca,dynamicTicks = T,tooltip = c("x","y",label = list))

pca is a visualization of a PCA. sub is a data.frame that contains variable names.

sub <- PCA(dataframe)

pca <- fviz_pca_ind(sub, pointsize = "cos2", 
             pointshape = 21, fill = "#E7B800",
             repel = TRUE, # Avoid text overlapping (slow if many points)
             geom = c("text","point"), 
             xlab = "PC1", ylab = "PC2",label = animal_list
             )

dataframe contains variable names and I want interactive to show those in the tooltip. tooltip = does not help me much and changing properties in pca_individuals (like with label= or something is not working either. Thank you for your kind support. I really appreciate your altruistic behaviour.

For playing around (the actual data frame is muuch bigger):

dataframe <- data_frame("c1"=c(78,89,0),"c2"=c(89,89,34),"c3"=c(56,0,4))


Solution

  • You can manually do the contents of the tooltips as follows:

    library(factoextra)
    library(plotly)
    library(FactoMineR)
    
    dataframe <- 
      data.frame("c1"=c(78,89,0),"c2"=c(89,89,34),"c3"=c(56,0,4))
    res.pca <- PCA(dataframe)
    
    pca <- fviz_pca_ind(res.pca, pointsize = "cos2", 
                        pointshape = 21, fill = "#E7B800",
                        repel = TRUE, 
                        geom = c("text","point"), 
                        xlab = "PC1", ylab = "PC2")
    
    ggly <- ggplotly(pca)
    bggly <- plotly_build(ggly)
    bggly$x$data[[1]]$text <- 
      with(pca$data, paste0("name: ", name, 
                            "</br></br>x: ", x, 
                            "</br>y: ", y, 
                            "</br>coord: ", coord, 
                            "</br>cos2: ", cos2, 
                            "</br>contrib: ", contrib))
    
    bggly