[英]Add a regression line to my scatterplot in r shiny
所以我構建了一個閃亮的應用程序,允許您根據我的數據集中的變量的任意組合創建散點圖。 它還在單獨的選項卡上輸出回歸模型的摘要。
基本上我想要一個選項來向我的散點圖添加回歸線。 這將基於從 UI 中選擇的輸入來創建散點圖。 我做了一些嘗試,但沒有成功。 這是我到目前為止的工作代碼:
pageWithSidebar(
titlePanel("Plotting weather trends 2010 - 2014"),
sidebarPanel(
selectInput("xCol", "Please select an x variable", names(DF2)),
selectInput("yCol", "Please select a y variable", names(DF2)),
checkboxInput("line", "Show regression line?", value = TRUE),
selectInput("plot_type", "Select a secodary plot for X variable", choices = c("Boxplot", "Histogram"))),
mainPanel(tabsetPanel(type = "tabs",
tabPanel("Plots", (plotOutput("plot1")), plotOutput("plot2")),
tabPanel("Regression Model Summary", verbatimTextOutput(outputId = "RegSum"))
)
)
))
server = function(input, output){
DF3 = reactive({DF2[, c(input$xCol, input$yCol)]})
output$plot1 = renderPlot({plot(DF3(),
main = "Histogram of select variables")})
output$plot2 = renderPlot({
if (input$plot_type == "Boxplot") {boxplot(DF2[,input$xCol], main = "boxplot of X variable")}
if (input$plot_type == "Histogram") {hist(as.numeric(unlist(DF2[,input$xCol])),main = "Histogram of X variable", xlab = "X variable")}
})
lm1 <- reactive({lm(reformulate(input$xCol, input$yCol), data = DF2)})
output$RegSum <- renderPrint({summary(lm1())})
}
shinyApp(ui = ui, server = server)
之前的嘗試包括添加一個 abline(lm) 函數,從 UI 獲取輸入,但無濟於事。
任何幫助,將不勝感激。
你對abline
是正確的。 我猜你的問題是你如何指定lm
函數:如果用戶選擇兩個變量“xCol”和“yCol”,它們會在引號中傳遞給閃亮的服務器。 但是, lm
函數需要y ~ x
形式的公式符號。 為了解決這個問題,我會寫lm(get(input$yCol) ~ get(input$xCol), data=DF3())
。 這樣 R 在數據集中而不是全局環境中搜索。
這是基於內置 mtcars 數據集的可重現示例:
library(shiny)
ui <- fluidPage(
selectInput("xCol", "Please select an x variable", names(mtcars)),
selectInput("yCol", "Please select a y variable", names(mtcars)),
checkboxInput("line", "Show regression line?", value = TRUE),
plotOutput("plot")
)
server <- function(input, output, session) {
data <- reactive({mtcars[, c(input$xCol, input$yCol)]})
output$plot <- renderPlot({
plot(data())
if(input$line) {
model <- lm(get(input$yCol) ~ get(input$xCol), data=data())
abline(model)
}
})
}
shinyApp(ui, server)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.