вставка аннотации к выбросам с использованием r plotly

#r #plotly #ggplotly

#r #сюжетно #ggплотно

Вопрос:

Используя приведенный ниже набор данных iris, как мне получить идентификатор цветка при наведении курсора на выбросы library(plotly) ?

Я пробовал что-то вроде:

 iris_ids <- iris %>% 
  mutate(id = rownames(iris))

plot_ly(iris, y = ~Sepal.Length, x= ~Species, type = 'box') %>%
  layout(title = 'Box Plot',
         xaxis = list(title = "cond", showgrid = F),
         yaxis = list(title = "rating"),
         annotations = list(
           x = boxplot.stats(Species)$out,
           # use boxplot.stats() to get the outlier's y coordinate
           y = boxplot.stats(Sepal.Length)$out, 
           # I want the ID of the flower
           # of the outliers
           text = c("ID:", id),
           showarrow = FALSE,
           xanchor = "right"
         )
  ) %>%
  config(displayModeBar = FALSE)
 

А также попробовал использовать оболочку ggplotly:

 ggplotly(
  ggplot(iris_id, aes(x = Species, y = Sepal.Length))  
  geom_boxplot()
) %>%
  #....what goes here....
 

Я предпочитаю второй способ, потому что мне удобнее работать с тематикой в ggplot2, но я открыт для любых предложений!! Спасибо.

Ответ №1:

Попробуйте этот подход, наверняка вы сможете настроить его дальше:

 library(ggplot2)
library(plotly)
library(dplyr)
#Data
iris_ids <- iris %>% 
  mutate(id = rownames(iris))
#Plot
gg <- ggplotly(
  ggplot(iris_ids, aes(x = Species, y = Sepal.Length))  
    geom_boxplot()
) 
hoverinfo <- with(iris_ids, paste0("id: ", id, "</br></br>",
                                   "Sepal.Length: ", Sepal.Length, "</br>"))
gg$x$data[[1]]$text <- hoverinfo
gg$x$data[[1]]$hoverinfo <- c("text", "boxes")
gg
 

Вывод:

введите описание изображения здесь