MayaGans
MayaGans

Reputation: 1845

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.

Upvotes: 0

Views: 335

Answers (1)

Duck
Duck

Reputation: 39595

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:

enter image description here

Upvotes: 1

Related Questions