最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

r - Autoplot(ly): how can labels appear when hovering over points - Stack Overflow

programmeradmin10浏览0评论

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.

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.

Share Improve this question edited Nov 19, 2024 at 0:26 ramiro asked Nov 18, 2024 at 15:36 ramiroramiro 1039 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

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):

发布评论

评论列表(0)

  1. 暂无评论