选择/复制 R plotly 图表中的悬停文本

11
我想能够选择和复制 plotly 图表中的悬停文本。在 R API 中是否可以实现这一点? 例如,在此热力图中,当将鼠标悬停在坐标(X=a,Y=d)上时,可以看到悬停文本显示为:

x=a,

y=d,

z=0.71886

然而,该文本无法被选择。目标是将此文本内容显示在一个框内(也许通过右键单击相应的单元格),以便将文本内容复制到剪贴板中。 非常感谢您的帮助。

一种方法是使用Shiny。请参阅https://plot.ly/r/shiny-coupled-hover-events/。event_data()函数可以让您检索值,然后您可以将其显示在一个框内或进行其他计算等操作。 - royr2
非常感谢您的回复。我会仔细研究这个问题。 - JulienLag
1个回答

0
要选择/复制悬停文本,请使用event_data()(如royr2所说)
这是一个玩具示例,从andyblueyo的gist复制过来,我稍作编辑,使其在没有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)

很遗憾,在悬停区域中似乎无法直接选择和复制文本,所以只能使用这种间接的方法。不管怎样,希望能对你有所帮助!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接