MayaGans
MayaGans

Reputation: 1845

Add trendline data to Shiny Plotly on hover

I'm creating a plot using ggplotly() and I'd like the Spearman's rank correlation [I'm storing here as the reactive value rho] to appear when hovering over the line created with geom_smooth. I found an article on the plotly website for doing this in python (https://plot.ly/python/linear-fits/) but I'm unsure how to achieve this in R. Any help or leads appreciated!!

library(shiny)
library(plotly)

ui <- fluidPage(
  mainPanel(plotlyOutput("line_plot"),
            verbatimTextOutput("rho"))
  )

# Define server logic required to draw a histogram
server <- function(input, output) {

  # calculate rho to be printed over line
  rho <- reactive({ cor.test(x = iris$Sepal.Length, y = iris$Sepal.Width, method='spearman')[[4]] })

  output$rho <- renderText(paste0("rho: ", rho()))

  output$line_plot <- renderPlotly({
    p <- ggplotly(
      ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) +
        geom_point() +
        # would I add the tooltip text here?
        # I know I need it to be:
        # "<b> rho: </b>", rho(), "<br/>",
        geom_smooth(method=lm, se=FALSE, color = "red") +
        theme_minimal()
    )
  })

}

# Run the application 
shinyApp(ui = ui, server = server)

Upvotes: 0

Views: 306

Answers (1)

ismirsehregal
ismirsehregal

Reputation: 33417

You can add the unoffical aesthetics text:

library(shiny)
library(plotly)

ui <- fluidPage(
  mainPanel(plotlyOutput("line_plot"),
            verbatimTextOutput("rho"))
)

# Define server logic required to draw a histogram
server <- function(input, output) {

  # calculate rho to be printed over line
  rho <- reactive({ cor.test(x = iris$Sepal.Length, y = iris$Sepal.Width, method='spearman')[[4]] })

  output$rho <- renderText(paste0("rho: ", rho()))

  output$line_plot <- renderPlotly({
    p <- ggplotly(
      ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) +
        geom_point() +
        geom_smooth(method=lm, se=FALSE, color = "red", aes(text = paste0("<b> rho: </b>", rho()))) +
        theme_minimal()
    ) 
  })

}

# Run the application 
shinyApp(ui = ui, server = server)

Result

Upvotes: 1

Related Questions