简体   繁体   中英

Interactive Scatter plot in R using Plotly and Shiny

I am relatively new to Shiny and Plotly and have the following code snippet:

#
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
#    http://shiny.rstudio.com/
#

library(shiny)
library(plotly)
library(odbc)
library(DBI)



# Define UI for application that draws a histogram
ui <- fluidPage(

   # Application title
   titlePanel("Demo"),

   #Sidebar with a slider input for number of bins
   sidebarLayout(
      sidebarPanel(
         sliderInput("bins",
                     "Number of bins:",
                     min = 0,
                     max = 100,
                     value = 70)
      ),

      # Show a plot of the generated distribution
      mainPanel(
        tabPanel("Heading", plotlyOutput("tbTable"))

      )
   )
)

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

  QueriedData <- reactive({

    connn <- DBI::dbConnect(odbc::odbc(),.connection_string = "XXX", uid = "AB", pwd = "CD")
    lat_rec.df <- dbGetQuery(connn, "PQR")
    dbDisconnect(connn)
    lat_rec.df1
  })  


   output$tbTable <- renderPlotly({

     plot_ly(QueriedData(),x = ~TotalCount, y = ~MyScore, type = 'scatter', mode = 'markers')

  })

}

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

As you can see above, I am plotting a scatter plot of my dataframe which I have read from the Database (as mentioned in the reactive function). I have a couple of questions here:

  1. I want to use the slider bar input as my Y Axis (MyScore). How do I do that? I am currently unable to link slider bar (bins) into my plotly graph. I want the scatter plot to update as per the slider input.
  2. I am slightly confused about reactive functions. Does it mean that each time, I change the slider bar, the DB is going to get called (in reactive function)? How does it work?
  3. If I have other Database tables to read and plot in other areas, do I include it in the reactive function? Please advice.

Thanks in advance for all your help! Cheers!

My solutions/answers to your three questions.

1.As you want to know how to control Y axis with sliderInput below code explains how to do it.

library(shiny)
library(plotly)
library(DBI)
library(pool)

pool <- dbPool(drv = RMySQL::MySQL(),dbname = "db",host = "localhost",username = "root",password = "psw", port = 3306)
data <- dbGetQuery(pool, "SELECT * FROM testTable;")
ui <- fluidPage(
  titlePanel("Demo"),
  sidebarLayout(
    sidebarPanel(
      sliderInput("bins", "Number of bins:", min = 0, max = 100, value = 70)
    ),
    mainPanel(
      tabPanel("Heading", plotlyOutput("tbTable"), 
               plotOutput("basicPlot") # Added extra as an Example for 3rd question
               )
    )
  )
)
server <- function(input, output, session) {
  QueriedData <- reactive({
    df <- data[data$total <= input$bins,] # filtering datafarme based on sliderInput
    return(df)
  })
  output$tbTable <- renderPlotly({
    plot_ly(QueriedData(), x = ~count, y = ~total, type = 'scatter', mode = 'markers')
  })
  # Added extra as an Example for 3rd question
  output$basicPlot <- renderPlot({
    data_for_plot <- dbGetQuery(pool, "SELECT * FROM dummyTable WHERE uid = 2018;")
    plot(x = data_for_plot$category, y = data_for_plot$performance, type = "p")
  })
}
shinyApp(ui = ui, server = server)

2.For reactivity it is better to fetch the table into a dataframe once, then place that dataframe in reactive environment. So that you can avoid multiple database calls. You can check in above code for the same.

3.Using of reactive environment purely depends on the requirement when you want to have interactivity with your shiny application. If you want to fetch the data from other tables and use in different plots, then no need to place your database connection string in reactive environment. Just query the database according to your requirement like in above code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM