English 中文(简体)
Select/copy hover text in R plotly graph
原标题:

I would like to be able to select and copy the hover text in plotly graphs. Is that possible with the R API? For example, in this heatmap, upon mousing over coordinates (X=a, Y=d), one can see the hover text displaying:

x=a,

y=d,

z=0.71886

However, the text is not selectable. The goal would be to e.g. display this text inside a box (perhaps by right-clicking on the corresponding cell) to be able to copy the text contents into the clipboard. Any help would be greatly appreciated.

问题回答

To select/copy the hover text, use event_data() (as royr2 said)

Here is a toy example as a demonstration, copied from andyblueyo s gist, with light editing from me, to get it working without a csv:

#install.packages("plotly")
library(plotly)
#install.packages("dplyr")
library(dplyr)
#install.packages("shiny")
library(shiny)
#install.packages("htmlwidgets")
library(htmlwidgets)

## Read the data set about ice cream
ice_cream_df <- tibble(
  flavors = c("guava sorbet", "ube", "chocolate", "strawberry", "mint chocolate chip", "honey lavender", "cookie dough", "peach", "cake batter"),
  images = c("http://image1.jdomni.in/product/B2/7D/07/Pink-Guava-Ice-cream_1497001650402_450X450.jpeg", "http://i.pinimg.com/originals/39/b0/00/39b0008a59c93aea26bcb8f44273cc6d.jpg", "http://www.brighteyedbaker.com/wp-content/uploads/2012/09/Chocolate-Ice-Cream.jpg", "http://a9lumux160-flywheel.netdna-ssl.com/wp-content/uploads/2017/05/Strawberry-Ice-Cream-1-800x1200.jpg", "http://d1wv4dwa0ti2j0.cloudfront.net/live/img/production/detail/ice-cream/cartons_rich-creamy_mint-chocolate-chip.jpg", "http://1.bp.blogspot.com/_ER9lTN0wb94/TEnLThTP48I/AAAAAAAAA6c/OUhS4vOtTJw/s640/lavender+ice+cream-1.jpg", "http://3.bp.blogspot.com/-Ip-XxFqrjrk/Vh6E7j6oS_I/AAAAAAAAaeo/9jEmP0Y7x3E/s1600/Chocolate-Chip-Pumpkin-Cookie-Dough-Ice-Cream-1.jpg", "http://www.browniebites.net/wp-content/uploads/2016/06/honeyed-peach-and-praline-ice-cream-recipe-01.jpg", "http://img.sndimg.com/food/image/upload/w_555,h_416,c_fit,fl_progressive,q_95/v1/img/recipes/12/89/52/f15xnUJJQc2kJB0O1v6o_birthday-cake-ice-cream-7207.jpg"),
  prices = c(5, 3, 4, 4, 5, 6, 4, 3, 3),
  scoops = c(4, 10, 5, 6, 3, 4, 8, 7, 5),
  rating = c(5, 4, 3, 4, 3, 5, 4, 3, 2),
  is.sherbet = c(TRUE, FALSE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE)
)
ice_cream_df

## Create the shiny UI layout
ui <- fluidPage(
  headerPanel("Price per Scoops"),
  sidebarPanel(
    sliderInput("priceRange", label = h3("Price Range"), min = 0, 
                max = 10, value = c(2, 8))
  ),
  mainPanel(
    plotlyOutput("icePlot"),
    h4("Click on the dots to learn more about the ice cream flavor."),
    h4("Use the lasso/box select to learn more about the ratings of each ice cream flavor."),
    plotlyOutput("ratingPlot"),
    uiOutput("imageLink")
  )
)

## Create the Shiny Server layout
server <- function(input, output) {
  ## Create the plotly plot that compares price vs scoops
  output$icePlot <- renderPlotly({
    range.ice.cream <- ice_cream_df %>% 
    filter(prices >= input$priceRange[1]) %>% 
    filter(prices <= input$priceRange[2])
    plot_ly(range.ice.cream, 
            x = ~prices, y = ~scoops, 
            type = "scatter", mode = "markers",
            text = ~paste("Flavor:", flavors), 
            key = ~images, 
            source = "imgLink") %>% 
            layout(title = paste("Ice Cream Price vs Scoops Given")) 
  })
  
  ## Create text paragraph of info on a selected point
  output$imageLink <- renderText({
    event.data <- event_data(event = "plotly_click", source = "imgLink")
    if (is.null(event.data)) {
      print("Click to see the link of the point.")
    } else { 
      ice.cream <- ice_cream_df %>% filter(images == event.data$key)
      HTML( <p>Flavor: ,ice.cream$flavors, 
           </p> , <p>X Value: , event.data[["x"]], 
           </p> , <p>Y Value: , event.data[["y"]], </p> ,
            <a href=" , ice.cream$images, "> , 
           ice.cream$images, </a> , <p> ,
            <img src=" ,ice.cream$images,  "/> , </p> )
    }
  })
  
  ## Create the plotly plot of price vs rating based on selection
  output$ratingPlot <- renderPlotly({
    event.data <- event_data(event = "plotly_selected", source = "imgLink")
    if (is.null(event.data)) {
      print("Click and drag events (i.e., select/lasso) to make the bar plot appear here")
      plot_ly(ice_cream_df, x = ~flavors, y = ~rating, type = "bar",
              text = ~paste("Flavor:", flavors)) %>%
              layout(title = paste("Ice Cream Ratings Given by Flavor"))
    } else {
      ice.cream <- ice_cream_df[ice_cream_df$images %in% event.data$key,]
      plot_ly(ice.cream, x = ~flavors, y = ~rating, type = "bar",
              text = ~paste("Flavor:", flavors), key = ~images, source = "imgLink") %>%
              layout(title = paste("Ice Cream Ratings Given by Flavor"))
    }
  })
}

shinyApp(ui = ui, server = server)

It doesn t appear to be possible to directly select and copy text in the hover area, sadly, so this indirect method will have to do. Anyway, hope it helps!





相关问题
How to plot fitted model over observed time series

This is a really really simple question to which I seem to be entirely unable to get a solution. I would like to do a scatter plot of an observed time series in R, and over this I want to plot the ...

REvolution for R

since the latest Ubuntu release (karmic koala), I noticed that the internal R package advertises on start-up the REvolution package. It seems to be a library collection for high-performance matrix ...

R - capturing elements of R output into text files

I am trying to run an analysis by invoking R through the command line as follows: R --no-save < SampleProgram.R > SampleProgram.opt For example, consider the simple R program below: mydata =...

R statistical package: wrapping GOFrame objects

I m trying to generate GOFrame objects to generate a gene ontology mapping in R for unsupported organisms (see http://www.bioconductor.org/packages/release/bioc/vignettes/GOstats/inst/doc/...

Changing the order of dodged bars in ggplot2 barplot

I have a dataframe df.all and I m plotting it in a bar plot with ggplot2 using the code below. I d like to make it so that the order of the dodged bars is flipped. That is, so that the bars labeled "...

Strange error when using sparse matrices and glmnet

I m getting a weird error when training a glmnet regression. invalid class "dgCMatrix" object: length(Dimnames[[2]]) must match Dim[2] It only happens occasionally, and perhaps only under larger ...

Generating non-duplicate combination pairs in R

Sorry for the non-descriptive title but I don t know whether there s a word for what I m trying to achieve. Let s assume that I have a list of names of different classes like c( 1 , 2 , 3 , 4 ) ...

Per panel smoothing in ggplot2

I m plotting a group of curves, using facet in ggplot2. I d like to have a smoother applied to plots where there are enough points to smooth, but not on plots with very few points. In particular I d ...

热门标签