如何在闪亮的应用程序中将corrplot保存为PDF?

如何在闪亮的应用程序中将corrplot保存为PDF?,r,pdf,shiny,download,R,Pdf,Shiny,Download,我试图将corrplot的输出保存到PDF文件中,并提供一个唯一的文件名选项。当我点击下载按钮时,它会在我的PDF查看器中打开PDF,并为它指定一个随机文件名-欢迎任何帮助,因为我是一个完全的新手,已经做了一周了 下面是代码-在代码下载部分的底部 library(shiny) library(shinythemes) library(psych) library(corrplot) library(RColorBrewer) library(Cairo) library(grDevices)

我试图将corrplot的输出保存到PDF文件中,并提供一个唯一的文件名选项。当我点击下载按钮时,它会在我的PDF查看器中打开PDF,并为它指定一个随机文件名-欢迎任何帮助,因为我是一个完全的新手,已经做了一周了

下面是代码-在代码下载部分的底部

library(shiny)
library(shinythemes)
library(psych) 
library(corrplot)
library(RColorBrewer)
library(Cairo)
library(grDevices)

# Correlation plot app with FDR option, which takes a CSV file
# containing species OTUs/ASVs and metabolites or clinical data
# see corrplot_test_data.csv

# Define UI for data upload app
# this section deals with the user interface (UI)
# and its design and format ----

not_sel <- "Not Selected"

about_page <- tabPanel(title = "About",
                       titlePanel("About"),
                       br(), "Correlation plot for species and metadata with False discovery rate adjustment")

instruction_page <- tabPanel(title = "Instructions",
                             titlePanel("Instructions"),
                             h4 ("Make sure all your inpit files are Comma seperated variable files (CSV)",
                             br(),
                             "Your input file needs to be in the format of Columns = species and variables (metabolite concs) and Rows = samples and as a CSV file",
                             br(),
                             "Your input file must not have any hyphens - or spaces in any of the rows and column headers and names.",
                             br(),
                             " Follow the running order i.e. start at 1 and then move to 2 etc",
                             br(),
                             "When you've finished click on the Analysis tab to see your plot"))


#ui <- fluidPage(    

# App title ----
#titlePanel("Uploading Files"),

# Sidebar layout with input and output definitions ----
main_page <-     tabPanel(title = "Analysis", titlePanel("Analysis"),
                          sidebarLayout(
                              
                              # Sidebar panel for inputs ----
                              sidebarPanel(
                                  
                                  
                                  
                                  # Input: Select number of rows to display ----
#                                  radioButtons("disp", "1: What do you wish to display in the files?",
#                                               choices = c(Head = "head",
#                                                           All = "all"),
#                                               selected = "head"),

                                  # Input: Select distance method ----
                                  radioButtons("dist", "1: Select Distance method for Correlation",
                                               inline = TRUE,
                                               choices = c(Spearman = "spearman",
                                                           Pearson = "pearson",
                                                           Kendall = "kendall"),
                                               selected = ";"),
                                  
                                  # Input: Select FDR method ----
                                  radioButtons("adjust_method", "2: Select false discovery rate adjustment method for Correlation",
                                               inline = TRUE,
                                               choices = c(Holm = "holm",
                                                           Hochberg = "hochberg",
                                                           Hommel = "hommel",
                                                           Bonferroni = "bonferroni",
                                                           Benjamini_Hochberg = "BH",
                                                           Benjamini_Yekutieli = "BY",
                                                           FDR = "fdr",
                                                           Pearson = "pearson",
                                                           Kendall = "kendall",
                                                           None = "none"),
                                               selected = ";"),
                                    # Input: Select display method ----
                                            radioButtons("shape", "3: Select the shape of the symbol in your plot",
                                                        inline = TRUE,
                                                        choices = c(Circle = "circle",
                                                            Square = "square",
                                                            Ellipse = "ellipse",
                                                            Number = "number",
                                                            Shade = "shade",
                                                            Colour = "color",
                                                            Pie = "pie"),
                                            selected = ";"),
                                    # Input: Select layout for matrix  ----
                                            radioButtons("layout", "4: Select the layout of your plot",
                                                         inline = TRUE,
                                                         choices = c(Full = "full",
                                                            Upper = "upper",
                                                            Lower = "lower"),
                                              selected = ";"),
                                    # Input: Select ordering of the correlation matrix  ----
                                            radioButtons("reordered", "5: Select the layout of your plot",
                                                         inline = TRUE,
                                                         choices = c(AOE = "AOE",
                                                            First_principal_component = "FPC",
                                                            Alphabet = "alphabet",
                                                            Hclust = "hclust"),
                                              selected = ";"),
                                    # Input: Select ordering of the correlation matrix  ----
                                            radioButtons("hclust_method", "6: Select the Hclust method if you chose this in 5",
                                                            inline = TRUE,
                                                            choices = c(Ward = "ward",
                                                            Single = "single",
                                                            Complete = "complete",
                                                            McQuitty = "mcquitty",
                                                            Median = "median",
                                                            Centroid = "centroid"),
                                            selected = ";"),

                                    # Size of labels in plot line ----
                                        sliderInput("text_size", "Text size for labels:",
                                                min = 0.05,
                                                max = 2,
                                                value = 0.5),

                                    # Size of labels in plot line ----
                                        sliderInput("number_size", "Text size for correlation coefficient when Number is chosen in 3:",
                                                min = 0.01,
                                                max = 2,
                                                value = 0.5),

                                    # Input: Select number of rows to display ----
                                        radioButtons("disp", "What do you wish to display in the Input data matrix panel?",
                                                        choices = c(Head = "head",
                                                        All = "all"),
                                                        selected = "head"),
 
                                    # Input: Select file 1 for Input data into corr.test ----
                                        fileInput("file1", "6: Choose Input data CSV File",
                                            multiple = TRUE,
                                            accept = c("text/csv","text/comma-separated-values,text/plain",".csv")),
                                    # Download the plot ----
                                        downloadButton('downloadPlot','Download Plot'),
                                        
                                  tags$hr(),
                                  
                              
                              ),
                              
                                  # Main panel for displaying outputs ----
                                   mainPanel(
                                  
                                  # Output: Data file ----
                                  tabsetPanel(
                                      tabPanel(title = "Input data matrix", tableOutput("shared")), # first panel
                                      tabPanel(title = "Correlation plot", plotOutput("corr_plot")) # second panel
                                             )
                                  #tableOutput("metadata")
                                  
                              )
                          )
)

# Define server logic to read selected file 
# this section deals with the functions and 
# analysis that will be performed in the 
# the app e.g. plots---

server <- function(input, output) {
    options(shiny.usecairo=T)
    
    output$shared <- renderTable({
        
        # input$file2 will be NULL initially. After the user selects
        # and uploads a file, head of that data file by default,
        # or all rows if selected, will be shown.
        
        req(input$file1)
        
        df <- read.csv(input$file1$datapath,
                       header = TRUE,
                       sep = ',' ,
                       quote = input$quote)
        
        if(input$disp == "head") {
            return(head(df))
        }
        else {
            return(df)
        }
        
    })
    
    output$corr_plot <- renderPlot({
        
        req(input$file1)
        
        # take CSV file of OTU data and make PCoA class for plotting
        rawdata <- read.csv(input$file1$datapath,header=T,row.names=1)
        mat <- as.data.frame(rawdata)
       
         # create correlation matrix
        corr_mat <- corr.test(mat, 
                              use = "pairwise",
                              method=input$dist,
                              adjust=input$adjust_method,
                              alpha=.05,
                              ci=TRUE,
                              minlength=5)
        
        corr_r_values <- corr_mat$r
        
        corr_p_values <- corr_mat$p
        
        # set colour palette for heatmap
        col=brewer.pal(n=11, name="RdYlBu")
        
        #plot heatmap of correlation matrix
             corrplot(corr_r_values, 
                      method = input$shape,
                      col=rev(col),
                      type = input$layout,
                      hclust.method = input$hclust_method,
                      order = input$reordered,
                      p.mat = corr_p_values, 
                      sig.level = 0.05,
                      insig = "blank",
                      addgrid.col = "#D3D3D3", # adjust for grid colour
                      tl.cex= input$text_size, # adjust for text size
                      number.cex = input$number_size, #adjust for number in plot size
                      pch.cex = "0.5", # input$text_size,
                      tl.col = "black", # adjust for text colour
                      diag = FALSE,
                      title=" ")

})
    #download corrplot output as PDF file
    
    output$downloadPlot <- downloadHandler(
        filename = function(){paste(" ", '.pdf', sep = '')},
        
        content = function(file){
            cairo_pdf(filename = file,
                      width = 18, height = 10, pointsize = 12, family = "sans", bg = "transparent",
                      antialias = "subpixel",fallback_resolution = 300)
            corrplot(corr_r_values, 
                     method = input$shape,
                     col=rev(col),
                     type = input$layout,
                     hclust.method = input$hclust_method,
                     order = input$reordered,
                     p.mat = corr_p_values, 
                     sig.level = 0.05,
                     insig = "blank",
                     addgrid.col = "#D3D3D3", # adjust for grid colour
                     tl.cex= input$text_size, # adjust for text size
                     number.cex = input$number_size, #adjust for number in plot size
                     pch.cex = "0.5", # input$text_size,
                     tl.col = "black", # adjust for text colour
                     diag = FALSE,
                     title=" ")
            dev.off()
        },
        
        contentType = "application/pdf"
    )    
    
    
    
    
}
# Run the app ----

ui <- navbarPage(title = "PCoA creator",theme = shinytheme('cerulean'),instruction_page,main_page,about_page)

shinyApp(ui = ui, server = server)
库(闪亮)
图书馆(shinythemes)
图书馆(心理学)
图书馆(corrplot)
图书馆(RColorBrewer)
图书馆(开罗)
图书馆(GR设备)
#带有FDR选项的关联图应用程序,该应用程序接受CSV文件
#包含种类OTU/ASV和代谢物或临床数据
#请参见corrplot\u test\u data.csv
#定义数据上传应用程序的用户界面
#本节介绍用户界面(UI)
#以及它的设计和格式----
我就是这样做的

library(shiny)
library(shinythemes)
library(psych) 
library(corrplot)
library(RColorBrewer)


# Correlation plot app with FDR option, which takes a CSV file
# containing species OTUs/ASVs and metabolites or clinical data
# see corrplot_test_data.csv

# Define UI for data upload app
# this section deals with the user interface (UI)
# and its design and format ----

not_sel <- "Not Selected"

about_page <- tabPanel(title = "About",
                       titlePanel("About"),
                       br(), "Correlation plot for species and metadata with False discovery rate adjustment")

instruction_page <- tabPanel(title = "Instructions",
                             titlePanel("Instructions"),
                             h4 ("Make sure all your inpit files are Comma seperated variable files (CSV)",
                             br(),
                             "Your input file needs to be in the format of Columns = species and variables (metabolite concs) and Rows = samples and as a CSV file",
                             br(),
                             "Your input file must not have any hyphens - or spaces in any of the rows and column headers and names.",
                             br(),
                             " Follow the running order i.e. start at 1 and then move to 2 etc",
                             br(),
                             "When you've finished click on the Analysis tab to see your plot"))


#ui <- fluidPage(    

# App title ----
#titlePanel("Uploading Files"),

# Sidebar layout with input and output definitions ----
main_page <-     tabPanel(title = "Analysis", titlePanel("Analysis"),
                          sidebarLayout(
                              
                              # Sidebar panel for inputs ----
                              sidebarPanel(

                                    # Input: Select distance method ----
                                            selectInput("dist", "1: Select Distance method for Correlation:",
                                                    list(`Distance Method` = list("spearman", "pearson", "kendall"))
                                                        ),

                                    # Input: Select FDR method ----
                                            selectInput("adjust_method", "2: Select false discovery rate adjustment method for Correlation:",
                                                    list(`Adjustment Method` = list("holm", "hochberg", "hommel", "bonferroni", "BH", "BY", "fdr", "pearson" , "kendall", "none"))
                                                        ),


                                    # Input: Select display method ----
                                            selectInput("shape", "3: Select the shape of the symbol in your plot",
                                                                list(`Shape` = list("square", "ellipse", "number", "shade", "color", "pie"))
                                                        ),


                                    # Input: Select layout for matrix  ----
                                            selectInput("layout", "4: Select the layout of your plot",
                                                            list(`Layout` = list("full", "upper", "lower"))
                                                        ),


                                    # Input: Select ordering of the correlation matrix  ----
                                                selectInput("reordered", "5: Select the layout of your plot",
                                                            list(`Ordering of data` = list("AOE", "FPC", "alphabet", "hclust"))
                                                            ),


                                    # Input: Select ordering of the correlation matrix  ----
                                                selectInput("hclust_method", "6: Select the Hclust method if you chose this in 5",
                                                        list(`Clustering method` = list("ward", "single", "complete", "mcquitty", "median", "centroid"))
                                                            ),


                                    # Size of labels in plot line ----
                                                sliderInput("text_size", "Text size for labels:",
                                                                min = 0.05,
                                                                max = 2,
                                                                value = 0.5),

                                    # Size of labels in plot line ----
                                                sliderInput("number_size", "Text size for correlation coefficient when Number is chosen in 3:",
                                                                min = 0.01,
                                                                max = 2,
                                                                value = 0.5),

                                    # Input: Select number of rows to display ----
                                        radioButtons("disp", "What do you wish to display in the Input data matrix panel?",
                                                        choices = c(Head = "head",
                                                        All = "all"),
                                                        selected = "head"),
 
                                    # Input: Select file 1 for Input data into corr.test ----
                                        fileInput("file1", "6: Choose Input data CSV File",
                                            multiple = TRUE,
                                            accept = c("text/csv","text/comma-separated-values,text/plain",".csv")),
                                    
                                    # Height slider bar
                                    sliderInput(inputId = "plot_height",
                                                label = "Plot heigth",                            
                                                min = 200, max = 1000, step = 10, value = 400),
                                    
                                    # Width slider bar
                                    sliderInput(inputId = "plot_width",
                                                label = "Plot width",                            
                                                min = 300, max = 1500, step = 10, value = 500),
                                    # Download the plot ----
                                        downloadButton('dbtn','Download Plot'),    
                                  tags$hr(),
                              ),
                              
                                  # Main panel for displaying outputs ----
                                   mainPanel(
                                  
                                  # Output: Data file ----
                                  tabsetPanel(
                                      tabPanel(title = "Input data matrix", tableOutput("shared")), # first panel
                                      tabPanel(title = "Correlation plot", plotOutput("corr_plot", width = "100%", height ="100%")) # second panel
                                             )
                                  #tableOutput("metadata")
                                  
                              )
                          )
)

# Define server logic to read selected file 
# this section deals with the functions and 
# analysis that will be performed in the 
# the app e.g. plots---

server <- function(input, output) {

    output$shared <- renderTable({
        
        # input$file2 will be NULL initially. After the user selects
        # and uploads a file, head of that data file by default,
        # or all rows if selected, will be shown.
        
        req(input$file1)
        
        df <- read.csv(input$file1$datapath,
                       header = TRUE,
                       check.names = FALSE,
                       sep = ',' ,
                       quote = input$quote)
        
        if(input$disp == "head") {
            return(head(df))
        }
        else {
            return(df)
        }
        
    })
    
    
        # creates a plot object called plot_obj which can be rendered and downloaded
        plot_obj <- reactive({
        
        req(input$file1)
        
        # take CSV file of OTU data and make PCoA class for plotting
        rawdata <- read.csv(input$file1$datapath,header=T,row.names=1, check.names=FALSE)
        mat <- as.data.frame(rawdata)
       
        # create correlation matrix
        corr_mat <- corr.test(mat, 
                              use = "pairwise",
                              method=input$dist,
                              adjust=input$adjust_method,
                              alpha=.05,
                              ci=TRUE,
                              minlength=5)
        # extract correlation values from corr_mat
        corr_r_values <- corr_mat$r
        
        # extract p values from corr_mat
        corr_p_values <- corr_mat$p
        
        # set colour palette for heatmap
        col=brewer.pal(n=11, name="RdYlBu")
        
        #plot heatmap of correlation matrix
             corrplot(corr_r_values, 
                      method = input$shape,
                      col=rev(col),
                      type = input$layout,
                      hclust.method = input$hclust_method,
                      order = input$reordered,
                      p.mat = corr_p_values, 
                      sig.level = 0.05,
                      insig = "blank",
                      addgrid.col = "#D3D3D3", # adjust for grid colour
                      tl.cex= input$text_size, # adjust for text size
                      number.cex = input$number_size, #adjust for number in plot size
                      pch.cex = "0.5", # input$text_size,
                      tl.col = "black", # adjust for text colour
                      diag = FALSE,
                      title=" ")

})
                # this part renders the plot object for presentation in the appropriate panel
                #data$Group <- env_data[[input$sel]]
                 output$corr_plot <- renderPlot({req(plot_obj())}, height = exprToFunction(input$plot_height), width = exprToFunction(input$plot_width))

        #download corrplot output as PDF file
                 output$dbtn <- downloadHandler(
                     filename = function(){paste(" ", '.pdf', sep = '')},
                     content = function(file) {
                         pdf(file)
                         #corrplot(plot_obj())
                         
                         req(input$file1)
                         
                         # take CSV file of OTU data and make PCoA class for plotting
                         rawdata <- read.csv(input$file1$datapath,header=T,row.names=1, check.names = FALSE)
                         mat <- as.data.frame(rawdata)
                         
                         # create correlation matrix
                         corr_mat <- corr.test(mat, 
                                               use = "pairwise",
                                               method=input$dist,
                                               adjust=input$adjust_method,
                                               alpha=.05,
                                               ci=TRUE,
                                               minlength=5)
                         # extract correlation values from corr_mat
                         corr_r_values <- corr_mat$r
                         
                         # extract p values from corr_mat
                         corr_p_values <- corr_mat$p
                         
                         # set colour palette for heatmap
                         col=brewer.pal(n=11, name="RdYlBu")
                         
                         corrplot(corr_r_values, 
                                  method = input$shape,
                                  col=rev(col),
                                  type = input$layout,
                                  hclust.method = input$hclust_method,
                                  order = input$reordered,
                                  p.mat = corr_p_values, 
                                  sig.level = 0.05,
                                  insig = "blank",
                                  addgrid.col = "#D3D3D3", # adjust for grid colour
                                  tl.cex= input$text_size, # adjust for text size
                                  number.cex = input$number_size, #adjust for number in plot size
                                  pch.cex = "0.5", # input$text_size,
                                  tl.col = "black", # adjust for text colour
                                  diag = FALSE,
                                  title=" ")
                         dev.off()
                     }
                 )

    
}
# Run the app ----

ui <- navbarPage(title = "PCoA creator",theme = shinytheme('cerulean'),instruction_page,main_page,about_page)

shinyApp(ui = ui, server = server)
库(闪亮)
图书馆(shinythemes)
图书馆(心理学)
图书馆(corrplot)
图书馆(RColorBrewer)
#带有FDR选项的关联图应用程序,该应用程序接受CSV文件
#包含种类OTU/ASV和代谢物或临床数据
#请参见corrplot\u test\u data.csv
#定义数据上传应用程序的用户界面
#本节介绍用户界面(UI)
#以及它的设计和格式----

大家好,这已经在Shinny R studio论坛上解决了