Raul
Raul

Reputation: 271

Rename and Remove Plotly Hover information

I am currently exploring Plotly outputs in Shiny and was wondering if there was a way of removing and renaming the information that appears when you hover on each observation. I have seen some examples in the site but none of them work directly with ggplot graphs being plugged into renderPlotly()

In my case I am trying to remove the Year information and rename count to Count. Any suggestions?

Sample code:

library(shiny)
library(tidyverse)
library(plotly)

A <- structure(list(Year = c(2020, 2021, 2021), Size = c(
  "L", "M",
  "S"
), count = c(83L, 93L, 216L)), row.names = c(NA, -3L), groups = structure(list(
  Year = c(2020, 2021), .rows = structure(list(1L, 2:3), ptype = integer(0), class = c(
    "vctrs_list_of",
    "vctrs_vctr", "list"
  ))
), row.names = c(NA, -2L), class = c(
  "tbl_df",
  "tbl", "data.frame"
), .drop = TRUE), class = c(
  "grouped_df",
  "tbl_df", "tbl", "data.frame"
))

ui <- fluidPage(
  titlePanel("Test Remove/Rename"),
  sidebarLayout(
    sidebarPanel(),
    mainPanel(
      plotlyOutput(outputId = "test")
    )
  )
)

server <- function(input, output) {
  output$test <- renderPlotly({
    ggplot(A, aes(Year, count, fill = Size)) +
      geom_col()
  })
}

shinyApp(ui = ui, server = server)

Upvotes: 0

Views: 621

Answers (1)

Tom
Tom

Reputation: 602

I would rename the variable count first and then pass it through ggplotly, setting the tooltip argument accordingly.

output$test <- renderPlotly({
    p <- A %>% 
      rename(Count = count) %>% 
      ggplot(aes(Year, Count, fill = Size)) +
      geom_col()
    p %>% ggplotly(tooltip = c('Count','Size'))
  })

Upvotes: 1

Related Questions