rplotlypcabiplot

Observation number as marker in PCA using Plotly in R


Below is the base code for visualizing a Principal Components Analysis (PCA) using Plotly in R. It is taken from the Plotly website.

library(plotly)
library(stats)
data(iris)
X <- subset(iris, select = -c(Species))
prin_comp <- prcomp(X, rank. = 2)
components <- prin_comp[["x"]]
components <- data.frame(components)
components <- cbind(components, iris$Species)
components$PC2 <- -components$PC2

fig <- plot_ly(components, x = ~PC1, y = ~PC2, color = ~iris$Species, colors = c('#636EFA','#EF553B','#00CC96'), type = 'scatter', mode = 'markers')%>%
  layout(
legend=list(title=list(text='color')),
plot_bgcolor='#e5ecf6',
xaxis = list(
  title = "0",
  zerolinecolor = "#ffff",
  zerolinewidth = 2,
  gridcolor='#ffff'),
yaxis = list(
  title = "1",
  zerolinecolor = "#ffff",
  zerolinewidth = 2,
  gridcolor='#ffff'))
fig

Is there a way to make the markers text instead? Specifically, I would like the markers to show the observation number, which is essentially the row number.

I looked into setting the annotations as text, but can't find a way to make them the observation number. All comments appreciated.


Solution

  • We can use the hovertext argument in the plot_ly call to include the obs number in the hover box:

    plot_ly(components, x = ~PC1, y = ~PC2, 
            color = ~iris$Species, colors = c('#636EFA','#EF553B','#00CC96'), 
            type = 'scatter', mode = 'markers',
            hovertext = paste("Observation", seq(nrow(components)))) %>%
      layout(
        legend=list(title=list(text='color')),
        plot_bgcolor='#e5ecf6',
        xaxis = list(
          title = "0",
          zerolinecolor = "#ffff",
          zerolinewidth = 2,
          gridcolor='#ffff'),
        yaxis = list(
          title = "1",
          zerolinecolor = "#ffff",
          zerolinewidth = 2,
          gridcolor='#ffff'))
    

    enter image description here

    In this picture you can see we are hovering over the 45th observation