如何使ui.R和server.R从其他文件中导入函数和数据并在ShinyApp中绘图

时间:2017-03-31 14:05:27

标签: r shiny rstudio

我有三个部分的文件,我想用来制作Shiny app。

coolplot.R

这是一个存储绘图功能的代码。

library(ggplot2)
library(tidyverse)
library(ggrepel)

#-------------------------
# Function 
#-------------------------
plotit <- function (dat, x_thres, y_thres) {
  dat["Significant"] <- ifelse((dat$wt > x_thres | 
                                  dat$mpg > y_thres ), 'NotSignif','Signif')
  p <- ggplot(dat, aes(wt, mpg)) + 
       geom_point(alpha=0.8,size=2.75, aes(color=Significant)) +
       scale_color_manual(values=c("#B94024","#7D8D87")) +
       geom_vline(xintercept= x_thres, colour = '#B94024') + 
       geom_hline(yintercept=y_thres, colour = '#B94024') +
       geom_text_repel(data=subset(dat, wt > x_thres | mpg > y_thres),
                       aes(wt,mpg,label=model),
                       box.padding = unit(0.35, "lines"),
                       point.padding = unit(0.3, "lines") 
                       )  + 
       theme(legend.position="none")  

  return(p)

}

#-------------------------
# Begin main code
#-------------------------
# I literally want to use file as input not 
# default mtcars variable
infile <- "https://gist.githubusercontent.com/seankross/a412dfbd88b3db70b74b/raw/5f23f993cd87c283ce766e7ac6b329ee7cc2e1d1/mtcars.csv"
dat <- read_delim(infile,delim=",", col_types = cols())  
y_thres <- 25
x_thres <- 3
plotit(dat, x_thres, y_thres)

该函数基本上采用x-threshold和y-threshold 并制作如下情节:

enter image description here

然后我尝试构建了允许用户使用的Shiny应用程序 基于相同的输入数据滑过x阈值和y阈值 并调用plotit函数。当它们滑动时,垂直的水平红线和标记点会相应地改变。

我的Shiny个应用文件是:

server.R

library(shiny)

# Define server logic for slider examples
function(input, output) {

  # Reactive expression to compose a data frame containing all of
  # the values
  sliderValues <- reactive({

    # Compose data frame
    data.frame(
      Name = c("X-threshold", 
               "Y-threshold"
               ),
      Value = as.character(c(input$integer, 
                             input$integer
                             )), 
      stringsAsFactors=FALSE)
  }) 

  # Show the values using an HTML table
  output$values <- renderTable({
    sliderValues()
  })
}

ui.R

library(shiny)

# Define UI for slider demo application
fluidPage(

  #  Application title
  titlePanel("Sliders"),

  # Sidebar with sliders that demonstrate various available
  # options
  sidebarLayout(
    sidebarPanel(
      # Simple integer interval
      sliderInput("integer", "X-threshold",
                  min=3, max=10, value=1),

      # Simple integer interval
      sliderInput("integer", "Y-threshold",
                  min=10, max=35, value=1)

    ),

    # Show a table summarizing the values entered
    mainPanel(
      tableOutput("values")
      # How can I output the plot from coolplot.R here????
    )
  )
)

我的问题是如何从ui.Rplot.R进行DataSourceInitializer导入功能 显示情节?

目前,Shiny在RStudio中看起来像这样(减去我的评论)。

enter image description here

1 个答案:

答案 0 :(得分:2)

你想要的是什么?请确保您的滑块有唯一的名称

library(ggplot2)
library(tidyverse)
library(ggrepel)
library(shiny)
#-------------------------
# Function 
#-------------------------
plotit <- function (dat, x_thres, y_thres) {
  dat["Significant"] <- ifelse((dat$wt > x_thres | 
                                  dat$mpg > y_thres ), 'NotSignif','Signif')
  p <- ggplot(dat, aes(wt, mpg)) + 
    geom_point(alpha=0.8,size=2.75, aes(color=Significant)) +
    scale_color_manual(values=c("#B94024","#7D8D87")) +
    geom_vline(xintercept= x_thres, colour = '#B94024') + 
    geom_hline(yintercept=y_thres, colour = '#B94024') +
    geom_text_repel(data=subset(dat, wt > x_thres | mpg > y_thres),
                    aes(wt,mpg,label=model),
                    box.padding = unit(0.35, "lines"),
                    point.padding = unit(0.3, "lines") 
    )  + 
    theme(legend.position="none")  

  return(p)

}

#-------------------------
# Begin main code
#-------------------------
# I literally want to use file as input not 
# default mtcars variable
infile <- "https://gist.githubusercontent.com/seankross/a412dfbd88b3db70b74b/raw/5f23f993cd87c283ce766e7ac6b329ee7cc2e1d1/mtcars.csv"
dat <- read_delim(infile,delim=",", col_types = cols())  
y_thres <- 25
x_thres <- 3
plotit(dat, x_thres, y_thres)



ui <- shinyUI(
  fluidPage(

    #  Application title
    titlePanel("Sliders"),

    # Sidebar with sliders that demonstrate various available
    # options
    sidebarLayout(
      sidebarPanel(
        # Simple integer interval
        sliderInput("integer", "X-threshold",
                    min=3, max=10, value=1),

        # Simple integer interval
        sliderInput("integer2", "Y-threshold",
                    min=10, max=35, value=1)

      ),

      # Show a table summarizing the values entered
      mainPanel(
        tableOutput("values"),
        plotOutput("myplot")
        # How can I output the plot from coolplot.R here????
      )
    )
  )
)

server <- shinyServer(function(input, output, session) {
  # Reactive expression to compose a data frame containing all of
  # the values

  sliderValues <- reactive({

    # Compose data frame
    data.frame(Name = c("X-threshold", "Y-threshold"),
      Value = as.character(c(input$integer, input$integer2)), 
      stringsAsFactors=FALSE)
  }) 

  # Show the values using an HTML table
  output$values <- renderTable({
    sliderValues()
  })

  output$myplot <- renderPlot({

    plotit(dat, input$integer, input$integer2)
  })

})

shinyApp(ui = ui, server = server)

enter image description here

编辑:从文件中加载绘图功能

<强> coolplot.R

library(ggplot2)
library(tidyverse)
library(ggrepel)

#-------------------------
# Function 
#-------------------------
#-------------------------
# Begin main code
#-------------------------
# I literally want to use file as input not 
# default mtcars variable
infile <- "https://gist.githubusercontent.com/seankross/a412dfbd88b3db70b74b/raw/5f23f993cd87c283ce766e7ac6b329ee7cc2e1d1/mtcars.csv"
dat <- read_delim(infile,delim=",", col_types = cols())  

plotit <- function (dat, x_thres, y_thres) {
  dat["Significant"] <- ifelse((dat$wt > x_thres | 
                                  dat$mpg > y_thres ), 'NotSignif','Signif')
  p <- ggplot(dat, aes(wt, mpg)) + 
    geom_point(alpha=0.8,size=2.75, aes(color=Significant)) +
    scale_color_manual(values=c("#B94024","#7D8D87")) +
    geom_vline(xintercept= x_thres, colour = '#B94024') + 
    geom_hline(yintercept=y_thres, colour = '#B94024') +
    geom_text_repel(data=subset(dat, wt > x_thres | mpg > y_thres),
                    aes(wt,mpg,label=model),
                    box.padding = unit(0.35, "lines"),
                    point.padding = unit(0.3, "lines") 
    )  + 
    theme(legend.position="none")  

  return(p)
}

闪亮的部分

   library(shiny)
    source("coolplot.R",local = TRUE)$value

    ui <- shinyUI(
      fluidPage(

        #  Application title
        titlePanel("Sliders"),

        # Sidebar with sliders that demonstrate various available
        # options
        sidebarLayout(
          sidebarPanel(
            # Simple integer interval
            sliderInput("integer", "X-threshold",
                        min=3, max=10, value=1),

            # Simple integer interval
            sliderInput("integer2", "Y-threshold",
                        min=10, max=35, value=1)

          ),

          # Show a table summarizing the values entered
          mainPanel(
            tableOutput("values"),
            plotOutput("myplot")
            # How can I output the plot from coolplot.R here????
          )
        )
      )
    )

    server <- shinyServer(function(input, output, session) {
      # Reactive expression to compose a data frame containing all of
      # the values

      # Add the source file of the plot if necessary

      sliderValues <- reactive({

        # Compose data frame
        data.frame(Name = c("X-threshold", "Y-threshold"),
          Value = as.character(c(input$integer, input$integer2)), 
          stringsAsFactors=FALSE)
      }) 

      # Show the values using an HTML table
      output$values <- renderTable({
        sliderValues()
      })

      output$myplot <- renderPlot({

        plotit(dat, input$integer, input$integer2)
      })

    })

    shinyApp(ui = ui, server = server)