简体   繁体   中英

boxplot annotation to outliers using r plotly

Using the iris dataset below how do I get the ID of the flower on hover of the outliers library(plotly) ?

I've tried something like:

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)

And also tried using the ggplotly wrapper:

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

I prefer the second way because I'm more comfortable with theming in ggplot2 but I'm open to any and all suggestions.! Thank you.

Try this approach, for sure you can customize further:

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

Output:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM