悬停时将趋势线数据添加到Shiny Plotly

时间:2019-12-04 15:28:34

标签: r shiny plotly ggplotly

我正在使用ggplotly()创建一个图,我希望将Spearman的等级相关性[我在这里存储为有效值rho]悬停在{ {1}}。我在plotly网站上找到了一篇文章,介绍了如何在python(https://plot.ly/python/linear-fits/)中执行此操作,但是我不确定如何在R中实现此功能。任何帮助或潜在客户都感激!!

geom_smooth

1 个答案:

答案 0 :(得分:1)

您可以添加非官方的美学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