[英]Plotly scatter plot in Shiny in R; plot is not updating nor is it fully interactive
[英]Interactive Scatter plot in R using Plotly and Shiny
我对 Shiny 和 Plotly 比较陌生,有以下代码片段:
#
# 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)
正如您在上面看到的,我正在绘制我从数据库中读取的数据框的散点图(如反应函数中所述)。 我在这里有几个问题:
在此先感谢您的帮助! 干杯!
我对您三个问题的解决方案/答案。
1.如果您想知道如何使用滑块输入控制 Y 轴,下面的代码解释了如何操作。
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.对于反应性,最好将表一次提取到数据帧中,然后将该数据帧放入反应环境中。 这样就可以避免多次数据库调用。 您可以在上面的代码中签入相同的内容。
3. reactive
环境的使用完全取决于您希望与闪亮的应用程序进行交互时的需求。 如果你想从其他表中获取数据并在不同的图中使用,那么不需要将你的数据库连接字符串放在反应环境中。 只需像上面的代码一样根据您的要求查询数据库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.